RPN计算器c++问题

RPN calculator c++ issues

本文关键字:问题 c++ 计算器 RPN      更新时间:2023-10-16

我需要创建一个在输入文件上操作的RPN计算器。它使用4个标准算术运算符以及pow和%。我不知道为什么下面的程序不能为最后4个输入行工作。我得到了最后4行"语法错误"的输出。有什么想法或建议吗?我使用的示例输入.txt文件是:

5 * -

7

4 * 8 30 +

香蕉

9 10 + 30 -

  1. 7 3-+ 2 -3+

40.65 900 -20 +

45.2 - 23.999%

2

正确的输出应该是:

-17年

7

语法错误

语法错误-11年

9

879.35

21.201100年

#include<iostream>
#include<fstream>
#include<string>
#include<stack>
#include<sstream>
#include<math.h> //pow
#define SPACE(b) if (!(b)) throw "";
using namespace std;
double evalrpn(stack<string> & tkline);
int main(void){
    string line;
    ifstream inputfile;
    string fileloc;
one:cout << "Enter the location of the input file: ";
    getline(cin, fileloc);
    inputfile.open(fileloc);
    while (inputfile.fail())
    {
        cout << "The file at location " << fileloc << " failed to open." << endl;
    goto one;
}
while (getline(inputfile, line)){
    stack<string> tkline;
    istringstream sstr(line);
    string tk;
    while (sstr >> tk)
        tkline.push(tk);
    if (!tkline.empty())
        try {
        auto z = evalrpn(tkline);
        SPACE(tkline.empty());
        cout << z << endl;
    }
    catch (...) { cout << "SYNTAX ERROR" << endl; }
    }

cin.ignore();
return 0;
}
double evalrpn(stack<string> & tkline){
SPACE(!tkline.empty());
double x, y;
auto tk = tkline.top();
tkline.pop();
auto n = tk.size();
if (n == 1 && string("+-*/%'pow'").find(tk) != string::npos) {
    y = evalrpn(tkline);
    x = evalrpn(tkline);
    if (tk[0] == '+') x += y;
    else if (tk[0] == '-') x -= y;
    else if (tk[0] == '*') x *= y;
    else if (tk[0] == '/') x /= y;
    else if (tk[0] == '%') x = fmod(x,y);
    else pow(x, y);
}
else {
    unsigned i; x = stod(tk, &i);
    SPACE(i == n);
}
return x;
}

您的程序不会处理令牌之间没有空格的情况,因为istringstream不会为您处理这种情况。您将不得不使用比按空格分割为标记更智能的解析器。