0

我需要创建一个从文本文件中读取的基本计算器。该文件的格式如下:

2
add 5 3
sub_prev 1
1 
mul 4 5

2代表运算的次数,显然add的意思是5+6,计算器保持之前的结果,这样就可以+-*/了。这意味着有 2 个操作:加 5 + 3,然后从前一个结果中减去 1。等等。

我的文件打开得很好,但不知道如何让它正确读取。理想情况下,它将读取第一个整数,进入一个读取正确后续行数的循环,然后执行操作。在for循环完成第一个操作后,它仍然在文件中读取while循环,但会重新进入for循环并读取和计算更多操作。

示例代码

while(myfile) // while reading the file
{
    int PR = 0; //initialize the previous result as 0
    myfile >> no; // grabbing the number of operations
    cout << no << endl; // testing to see if it got it correct

    for ( int i = 1; i <= no; i++) // for the number of operations
    {
        myfile >> no >> op >> x >> y; // read the lines
        if (op == "add") //there would be an if for each operation
        {
            PR = x + y;
        }
    }

    myfile >> no >> op >> x >> y;
}

问题是它从不想进入 for 循环,它读到 no (操作数为 2,但它继续通过 while 循环而不是进入 for 循环

**更新代码**

 while(myfile) // while reading the file
{
    int PR = 0; //initialize the previous result as 0
    myfile >> no; // grabbing the number of operations


    for ( int i = 1; i <= no; i++) // for the number of operations
    {
    myfile >> op;
    if (op == "add") 
    {
     myfile >> x  >> y;
     PR = x + y;
    }      

    if (op == "sub_prev")
    {
        myfile >> x;
        PR = PR - x;
    }  

    if (op == "mul")
    {
        myfile >> x >> y;
        PR = x * y;
        //cout << x << y << PR << endl; //testing mul operation 
    }

    }

    cout << "The result of operation " << " is " << PR << endl;


}

它计算正确,但输出错误:

Enter file name: newfile.txt
The result of operation  is 7
The result of operation  is 20
The result of operation  is 20

RUN SUCCESSFUL (total time: 3s)
4

1 回答 1

2

你在no这里修改

myfile >> no >> op >> x >> y; 

你不应该那样做。我建议将以下内容作为 for 循环的主体:

std::string operation;
myfile >> operation;
if (operation == "add") {
   int a, b;
   myfile >> a  >> b;
   PR = x + y;
} else if (operation == "sub_prev") {
   int value;
   myfile >> value;
   // do something
} else {
   // for other operations if added in future
}
于 2013-07-30T20:48:58.617 回答