Write an even better calculator program calc3.cpp that can understand squared numbers. We are going to use a simplified notation X^ to mean X2. For example, 10^ + 7 - 51^ should mean 102 + 7 − 512.
Example:
When reading input file formulas.txt
5^;
1000 + 6^ - 5^ + 1;
the program should report:
$ ./calc3 < formulas.txt //if this doesn't work g++ (yourfile).cpp
//then ./a < formulas.txt
25
1012
A hint:
To take into account ^, don’t add or subtract new numbers right away after reading them. Instead, remember the number, read the next operator and if it is a ^, square the remembered number, then add or subtract it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include <iostream>
using namespace std;
int readnumber() //this int prototype I found online it works though not sure how
{
int val;
cin >> val;
if (cin.peek() == '^')
{ // found ^
val *= val; // square the value
cin.ignore(); // remove the ^ so no one else trips over it
}
return val;
}
int main()
{
int result=0;
char op;
int operand=0;
result = readnumber();
cin >> result;
while (cin >> op >> operand) {
operand=readnumber();
if (op ==';')
{
cout<<result<<endl;
}
operand = readnumber();
switch(op)
{
case '+': //addition
result += operand;
break;
case '-': //subtraction
result -= operand;
break;
case ';': //end on semicolon
break;
}
cout<<result;
}
cout<<result;
}
}
|
I know this doesn't work and cout a 0 for result, I had to modify it so it won't resemble my code too much though I need help with the '^' and ';' statements because currently I only get 25 as the result when reading 5^ but it neglects the arithmetic in the second line of the .txt file which is 1000 + 6^ - 5^ + 1;. I wonder if anyone know how to get the second line of formulas.txt to work.