在文件中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
遇到困难,请问该怎么实现下面这个要求呀
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
bekote 2021-08-14 15:25关注#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; }本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 3无用