我为家庭作业写了这个程序。我没有得到正确的输出。我被告知这是因为我没有在计算集之间重置PreviousResult,但我不知道该怎么做。 输出应为:
请输入文件名:calc.txt
计算1的结果是:26
计算2的结果是:2
计算3的结果是:0
相反,我得到4次计算,计算3 = 1,4 = 0
calc.txt文件是:
3 加5 4 add_prev 4 mul_prev 2
1 sub 3 1
1 div_prev 2
我的代码:
// Header Files
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// Declaring variables
int PreviousResult = 0;
string command;
string filename = "calc.txt";
int x,y,z;
int result = 0;
int numCommands = 0;
int operation = 1;
//Prompts the user to enter the text file name.
cout << "Please enter a filename: ";
cin >> filename;
//Declaring an ifstream object and opening the file
ifstream myfile(filename.c_str());
myfile.open("calc.txt");
//Will check to see if file exists. If not, it will output the following.
if(!myfile)
{
cout << "The file doesn't exist." <<endl;
return 0;
}
//While loop- read the file until the end is reached.
while(!myfile.eof())
{
myfile >> numCommands;
for(int i = 0; i < numCommands; i++)
{
myfile >> command;
//Addition
if (command=="add")
{
myfile >> x >> y;
PreviousResult = x + y;
}
//Subtraction
else if (command == "sub")
{
myfile >> x >> y;
PreviousResult = x - y;
}
//Multiplication
else if (command == "mul")
{
myfile >> x >> y;
PreviousResult=x*y;
}
//Division
else if(command=="div")
{
myfile >> x >> y;
PreviousResult = x / y;
}
else if (command == "add_prev")
{
myfile >> z;
PreviousResult += z;
}
else if (command == "sub_prev")
{
myfile >> z;
PreviousResult -= z;
}
else if (command == "mul_prev")
{
myfile >> z;
PreviousResult *= z;
}
else if (command == "div_prev")
{
myfile >> z;
PreviousResult /= z;
}
}
result = PreviousResult;
//Print the results.
cout << "The result of calculation " << operation <<" is: " << result << endl;
//The count is incremented by 1
operation ++;
}
return 0;
}
答案 0 :(得分:1)
如果我正确地解释您的程序,那么您的一个问题是来自PreviousResult未被重置是正确的。您使用此行声明并初始化了PreviousResult
int PreviousResult = 0;
重置它就像重新分配其值(如
)一样简单PreviousResult = 0;
至于为什么你得到4个计算而不是3个,
while(!myfile.eof())
将比你想要的时间多循环1次,因为eof()仅在输入流读取文件结尾后返回false。这种情况直到发生
myfile >> numCommands;
。另一种选择是
while(myfile >> numCommands)
,当没有更多东西需要阅读时,while循环将终止。
答案 1 :(得分:0)
问题是您在执行计算后没有重置PreviousResult。因此,在计算2中,您将PreviousResult设置为2,设置result = PreviousResult,然后显示结果。问题是,一旦你进入计算3,PreviousResult仍然等于2.这意味着计算3是计算2除以2而不是0除以2,给你错误的答案。
因此,在设置Result = PreviousResult后,您需要行
PreviousResult = 0;
对于第4次计算,while(!myfile.eof())会导致结果不一致。可能有换行符导致它尝试读取下一个空行。在while循环的开头大括号之后添加myfile.ignore(),这应该可以解决问题。