题目
在文件中question.txt存放了以下运算表达式
add(23,45)
sub(44,12)
muti(3,5)
div(54,9)
doubleMe(5)
编写一个程序,从文件中读取每行的运算表达式,将计算结果存放于文件answer.txt中
add(23,45)=68
sub(44,12)=32
muti(3,5)=15
div(54,9)=6
doubleMe(5)=10
代码
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream myfile("question.txt");
if (!myfile.is_open())
{
cout << "can not open this file" << endl;
return 0;
}
ofstream outfile("answer.txt", ios::trunc);
string s, fun;
double a, b;
string c, d;
while(getline(myfile,s))
{
string fun = s.substr(0, s.find_first_of('('));
if (s.find_first_of(',') == string::npos){
c = s.substr(s.find_first_of('(') + 1, s.find_first_of(')') -s.find_first_of('(') -1);
istringstream iss(c);
iss >> a;
}
else{
c = s.substr(s.find_first_of('(') + 1, s.find_first_of(',') -s.find_first_of('(') -1);
d = s.substr(s.find_first_of(',') + 1, s.find_first_of(')') -s.find_first_of(',') -1);
istringstream issa(c);
issa >> a;
istringstream issb(d);
issb >> b;
}
double res = 0;
if(fun.compare("add") == 0){
res=a+b;
}
else if(fun.compare("sub") == 0){
res=a-b;
}
else if(fun.compare("muti") == 0){
res=a*b;
}
else if(fun.compare("div") == 0){
res=a/b;
}
else if(fun.compare("doubleMe") == 0){
res=a*2;
}
outfile << s <<"="<<res<<endl;
}
myfile.close();
outfile.close();
return 0;
}