0

我需要创建一个对输入文件进行操作的 RPN 计算器。它使用 4 个标准算术运算符以及 pow 和 %。我不确定为什么以下程序不适用于最后 4 行输入。我得到最后 4 行的“SYNTAX ERROR”输出。有什么想法或建议吗?我正在使用的示例输入 .txt 文件是:

3 4 5.0 * -

7

4 * 8 30 +

香蕉

9 10 + 30 -

  1. 7 3-+ 2 -3+

900 40.65-20+

45.2 23.999%

10 战俘 2

正确的输出应该是:

-17

7

语法错误

语法错误

-11

9

879.35

21.201

100

#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;
}
4

1 回答 1

1

Your program doesn't handle the case where there are no spaces between tokens, because istringstream doesn't handle that case for you. You're going to have to use a more intelligent parser than splitting into tokens by spaces.

于 2014-05-06T19:13:26.377 回答