In: Computer Science
C++ programming question
theNumbers.txt
144 + 26
3 * 18
88 / 4
22 – 8
16 / 2
20 * 20
-Your Program should read in all items, compute the answer to each expression (any decimals should be rounded to the nearest tenth), and output the answers to an output file of the user's choosing. The formatting of the output is that there is a set width of 10 characters for each answer, left aligned, with a new line character every 3 answers. A sample “answers.txt” is provided below. (not drawn to scale)
answers.txt
17000 54 22
14 8 400
-You may assume that the name of the text file that will be outputted to is always 20 characters or less.
-You may assume that there are only 4 possible operations ( + - * /), add, subtract, multiply, and decimal division, and that no other characters will show up as the middle symbol.
- Appropriate error messages should be displayed if the file cannot be opened.
- Extra Credit: The answers in the output file ONLY show a decimal if the answer is not a whole number answer.
If you have any doubts, please give me comment...
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
int main(){
int num1, num2, n;
double result;
char op;
ifstream inFile;
inFile.open("theNumbers.txt");
if(inFile.fail()){
cout<<"Unable to open file"<<endl;
return -1;
}
ofstream outFile;
outFile.open("answers.txt");
n = 1;
while(!inFile.eof()){
inFile>>num1>>op>>num2;
if(op=='+')
result = num1 + num2;
else if(op=='-')
result = num1 - num2;
else if(op=='*')
result = num1 * num2;
else
result = (double)num1 / num2;
outFile<<setw(10)<<left<<result;
if(n%3==0)
outFile<<endl;
n++;
}
cout<<"Successfully saved into answers.txt"<<endl;
outFile.close();
inFile.close();
return 0;
}