1

我正在编写一个程序,该程序接受用户输入并使用堆栈将中缀表达式转换为基于优先级的后缀表达式,操作数始终位于运算符之前。例如,如果用户输入:

(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++ 和一般编程很陌生,所以任何建议都会很棒。

4

3 回答 3

2
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);

这就是函数原型的语法。你确定这编译?

于 2011-01-23T07:54:17.377 回答
2

问题在这里:

bool prec (char a, char b, char c, char d);
return ('*' > '/' > '+' > '-');

我猜这是为了定义一个优先函数,但这不是它在做什么。第一行声明存在这样的函数(其参数与前几行中声明的变量无关),第二行导致整个程序终止。如果你想要这样的函数,你必须在外部定义它main

这里有一个稍微不那么引人注目的错误:

if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input)

首先,这部分

input == '*'||'/'||'+'||'-'

被解释为

(input == '*') || ('/') || ('+') || ('-')

最后三个条件是正确的,第一个是无关紧要的。而且我什至不确定s.top()如果 s 为空该怎么办。

这应该足够继续了。我建议您先构建和测试例程,例如,识别运算符并评估它们的优先级,然后再尝试将所有内容放在一个程序中。

于 2011-01-23T08:20:11.703 回答
0

Falmarri 是对的,只是想发布我的自我,它编译我试过了,但还有一件事:你说的是 else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Here?你确定甚至达到了这一点,因为当我运行它时,它只是停在:

while (cin.get(input) && input != '\n')

直到我按回车键,甚至更多,您可以在 cin.get(input) 中从 consol 输入多个字符,但输入将仅包含您输入的第一个字符。为了解决这个问题,我只是 #include <conio.h>在开头放了一个 used

while ((input = getch()) && input != (char)13) in staid of you're code  

简短的解释

getch()

仅按一个字符后返回

输入 != (char)13 需要代替 input != '\n' 因为 getch() return (char)13 for ENTER 请参阅 ASCII 表了解更多信息。

于 2011-01-23T08:10:19.910 回答