Task C. Calc2: Reading multiple formulas.
Write a better version of the calculator, calc2.cpp, that can evaluate multiple arithmetic expressions. Let’s use the semicolon symbol that must be used at the end of each expression in the input.
Assuming that the input file formulas.txt looks as follows:
15 ; 10 + 3 + 0 + 25 ; 5 + 6 - 7 - 8 + 9 + 10 - 11 ;
When we run the program with that input, the output should evaluate all of the expressions and print them each on its own line:
$ ./calc2 < formulas.txt 15 38 4
If you need any corrections/clarifications kindly comment.
Please give a Thumps Up if you like the answer.
Program
#include <iostream>
#include<fstream>
using namespace std;
int main() {
int num;
char op;
bool solved = false;
ifstream infile;
infile.open("formulas.txt");
infile>> num;
int result = num;
while (infile>> op >> num) { //Inputs
operators and the numbers
solved = false;
if (op == ';') {
cout <<
result << endl;
solved =
true;
result =
num;
}
if (!solved) {
// Keep calculating until
operator is ;
if (op ==
'+'){
result += num;
solved = true;
} else if (op ==
'-'){
result -= num;
solved = true;
}
}
}
if (solved) {
cout << result <<
endl;
}
return 0;
}
Output
15
38
4
formulas.txt
15 ;
10 + 3 + 0 + 25 ;
5 + 6 - 7 - 8 + 9 + 10 - 11 ;
Get Answers For Free
Most questions answered within 1 hours.