weixin_54795555 2021-08-14 13:45 采纳率: 33.3%
浏览 465
已结题

遇到困难,请问该怎么实现下面这个要求呀

在文件中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

  • 写回答

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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 8月22日
  • 已采纳回答 8月14日
  • 创建了问题 8月14日

悬赏问题

  • ¥15 使用MATLAB进行余弦相似度计算加速
  • ¥15 服务器安装php5.6版本
  • ¥15 我想用51单片机和数码管做一个从0开始的计数表 我写了一串代码 但是放到单片机里面数码管只闪烁一下然后熄灭
  • ¥20 系统工程中,状态空间模型中状态方程的应用。请猛男来完整讲一下下面所有问题
  • ¥15 我想在WPF的Model Code中获取ViewModel Code中的一个参数
  • ¥15 arcgis处理土地利用道路 建筑 林地分类
  • ¥20 使用visual studio 工具用C++语音,调用openslsx库读取excel文件的sheet问题
  • ¥100 寻会做云闪付tn转h5支付链接的技术
  • ¥15 DockerSwarm跨节点无法访问问题
  • ¥15 使用dify通过OpenAI 的API keys添加OpenAI模型时报了“Connection Error”错误