在C ++中使用Stacks for infix和postfix表达式

我正在编写一个程序,它接受用户输入并使用堆栈将基于优先级的中缀表达式转换为后缀表达式,操作数总是在运算符之前。例如,如果用户输入: (A + B * C) 那么程序应该显示: ABC * + 到目前为止,我有这个:
#include <iostream>
#include <stack>
#include <string>


using namespace std;

int main()
{
    stack<char> s;
    char input;
    while (cin.get(input) && input != 'n')
        {
            if (isalnum(input))
                cout << input << "n";
            else if (input == '(')
                s.push(input);
            else if (input == ')')
            {
        while (!s.empty() && s.top() != '(')
            {
            cout << s.top();
            s.pop();
        }
            if(!s.empty()) 
                    s.pop();
            else
                cout << "ERROR: No Matching ( n";
        }
     else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?
     {
         char a = '*';
         char b = '/';
         char c = '+';
         char d = '-';
         bool prec (char a, char b, char c, char d);
             return ('*' > '/' > '+' > '-');
             s.push(input);
     }
         else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
             while (!s.empty()) 
          {
              cout << s.top();
          s.pop();
                  s.push(input);
          }
        }
    while (!s.empty())
    {
        cout << s.top();
        s.pop();
    }
}
哪个编译并运行但不能正常运行。当输入类似“ab”的表达式时,程序将显示“ab”,但如果输入“a + b + c”,则仅显示“a”。这意味着程序不会将操作符放入堆栈中以便稍后显示。我需要帮助的是修改程序,以便在输入操作符时,它应该被添加到堆栈中,然后在操作数之后根据它的优先级(*> /> +> - )显示,当输入完成时。 我对C ++和编程很新,所以任何建议都会很棒。     
已邀请:
else if (input == '*'||'/'||'+'||'-' && s.top() >= input)
这不符合你的想法。你需要这样做
else if (input == '*'|| input == '/'|| input == '+'|| input == '-' && s.top() >= input)
这看起来也像是一个错误
bool prec (char a, char b, char c, char d);
这是函数原型的语法。你确定这个编译好吗?     
问题出在这里:
bool prec (char a, char b, char c, char d);
return ('*' > '/' > '+' > '-');
我猜这是为了定义一个优先级函数,但这不是它正在做的事情。第一行声明存在这样的函数(并且它的参数与前面行中声明的变量无关),第二行导致整个程序终止。如果你想要这样的函数,你必须在
main
之外定义它。 这里有一个稍微不那么引人注目的bug
if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input)
首先,这部分
input == '*'||'/'||'+'||'-'
被解释为
(input == '*') || ('/') || ('+') || ('-')
最后三个条款是真的,第一个是无关紧要的。如果s为空,我甚至不确定是什么.ѭ。 这应该足以继续下去了。我建议你首先构建和测试例程,例如,在尝试将所有内容放在一个程序中之前,识别运算符并评估它们的优先级。     
Falmarri是对的,只是想发布我的自己,并编译我尝试过,但还有另一件事:你说
else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Her
e?  你确定甚至达到了这一点,因为当我跑步时,它只是停在:
while (cin.get(input) && input != 'n')
直到我点击进入,甚至更多你可以在cin.get(输入)中从consol输入多个char,但输入将只包含你输入的第一个char。为了解决这个问题,我只想说一个
#include <conio.h>
一开始使用
while ((input = getch()) && input != (char)13) in staid of you're code  
简短的解释
getch()
只按一个字符后返回 输入!=(字符)13 在staid中是必需的 输入!=' n' 因为getch()返回(char)13对于ENTER,请参阅ASCII表以获取更多信息。     

要回复问题请先登录注册