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 に答える