[英]Using Stacks In C++ for infix and postfix expressions
我正在編寫一個程序,它接受用戶輸入並使用堆棧將基於優先級的中綴表達式轉換為后綴表達式,操作數總是在運算符之前。 例如,如果用戶輸入:
(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為空,我甚至不確定s.top()
做什么。
這應該足以繼續下去了。 我建議您在嘗試將所有內容放在一個程序中之前,先構建和測試可以識別運算符並評估其優先級的例程。
Falmarri是對的,只是想發布我的自己,它編譯我嘗試了,但還有另一件事:你說else if (s.empty() && input == '*'||'/'||'+'||'-' && s.top() < input) // Error Begins Her
嗎? 你確定甚至達到了這一點,因為當我跑步時,它只是停在:
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()
只按一個字符后返回
輸入!=(char)13在輸入!='\\ n'的staid中是必需的,因為getch()返回(char)13對於ENTER,請參閱ASCII表以獲取更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.