简单计算器C++

Simple Calculator C++

本文关键字:C++ 计算器 简单      更新时间:2023-10-16

我为家庭作业编写了这个程序。我没有得到正确的输出。有人告诉我,这是因为我不会在两组计算之间重置PreviousResult,但我不知道如何做到这一点。输出应为:

请输入文件名:calc.txt

计算1的结果是:26

计算2的结果是:2

计算3的结果是:0

相反,我得到了4次计算,其中计算3=1,4=0

calc.txt文件为:

3加5 4添加_修订4mul_prev2

1sub 3 1

1div_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;
  }

如果我正确地解释了您的程序,那么您的问题之一是由于PreviousResult没有重置。您在开始时用这行声明并初始化了PreviousResult

int PreviousResult = 0;

重置它就像重新分配其值(如)一样简单

PreviousResult = 0;

至于为什么你得到4次计算而不是3次,

while(!myfile.eof())

由于eof()只在输入流读取文件末尾后返回false,因此循环1的次数将比预期的多。直到CCD_ 1。另一种选择是进行

while(myfile >> numCommands)

而while循环将在没有更多内容要读取时终止。

问题是执行计算后没有重置PreviousResult。因此,在计算2中,您将PreviousResult设置为2,设置result=PreviousResults,然后显示结果。问题是,一旦进入计算3,PreviousResult仍然等于2。这意味着计算3是计算2除以2,而不是0除以2,从而给出错误的答案。

因此,在您设置Result=PreviousResult之后,您需要行

PreviousResult = 0;

至于第四次计算,while(!myfile.eof())可能会导致结果不一致。可能有换行符导致它尝试读取下一个空行。在while循环的左大括号后面添加myfile.ignore(),这应该可以解决问题。