我正在编写一个程序,该程序接受用户输入并使用堆栈将中缀表达式转换为基于优先级的后缀表达式,操作数始终位于运算符之前。例如,如果用户输入:
(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++ 和一般编程很陌生,所以任何建议都会很棒。