中缀的前缀?

时间:2018-04-08 23:24:22

标签: c++ variable-assignment prefix infix-notation

在我的班级中,我们的任务之一是将前缀方程转换为中缀。看完那部分后,我仍然不知道自己在做什么。这本书有一些代码可以在给出时解决前缀方程,但我不知道它是如何做到的,或者我将如何显示中缀版本。任何帮助都将在解释此代码如何找到解决方案以及如何让它显示中缀版本时受到赞赏。

#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;

int prefixExpr(istream &exprStream);

int main() {
string input;
cout << "Enter prefix expressions to evaluate. \nPress enter after each expression, and press enter on a blank line  to quit." << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
while (input.size() != 0){
    istringstream exprStream(input);
    cout << prefixExpr(exprStream) << endl;
    cout << "Enter a prefix expression to evaluate: ";
    getline(cin, input);
}
return 0;
}

int prefixExpr(istream &exprStream) {
char ch = exprStream.peek();
while (isspace(ch)) {
    ch = exprStream.get();
    ch = exprStream.peek();
}
cout << ch << endl;

if (isdigit(ch)) {
    int number;
    exprStream >> number;

    cout << number << endl;

    return number;
}
else {
    ch = exprStream.get();

    int value1 = prefixExpr(exprStream);
    int value2 = prefixExpr(exprStream);

    switch (ch) {
    case '+': return value1 + value2;
    case '-': return value1 - value2;
    case '*': return value1 * value2;
    case '/': return value1 / value2;
    default: cout << "Bad input expression";
        exit(1);
    }
}
}

0 个答案:

没有答案