[英]Postfix to infix with stacks.
我正在一個項目中,從后修復符號轉換為完全帶括號的中綴符號。 我遇到的問題是,它以與打印相反的順序打印/存儲為:
For line: QQ=
(Q=Q)
For line: ABC*D+*
((D+(C*B))*A)
For line: AB+CD+EF%G--*
(((G-(F%E))-(D+C))*(B+A))
For line: NT^G*NN+#
((N+N)#(G*(T^N)))
For line: A
A
For line: ABC*D+*
((D+(C*B))*A)
我的讀取數據的代碼是:
void ReadData(string inString, ifstream& in)
{
if (in.is_open())
{
stack<string> postToIn;
for (unsigned int i = 0; i< inString.length(); i++)
{
if ((inString[i] != '+') && (inString[i] != '-') && (inString[i] != '/') && (inString[i] != '#') &&
(inString[i] != '*') && (inString[i] != '%') && (inString[i] != '^') && (inString[i] != '='))
{
string charac(1,inString[i]);
postToIn.push(charac);
}
else
{
string temp = "";
temp += "(";
temp += postToIn.top();
postToIn.pop();
temp += inString[i];
temp += postToIn.top();
postToIn.pop();
temp += ")";
postToIn.push(temp);
}
}
while (!postToIn.empty())
{
cout << postToIn.top();
postToIn.pop();
}
cout << endl;
}
}
我不知道它在代碼的哪個位置反轉了它。 我知道堆棧是先進先出的。任何幫助將不勝感激。
堆棧頂部將在右側具有您想要的最新操作數。 當前實現將其放在運算符的左側。
string temp = "";
string temp2 = "";
temp += "(";
temp2 += postToIn.top(); // This is the recent operand. This needs to go on the right of the operator in infix notation
postToIn.pop();
temp += postToIn.top();
postToIn.pop();
temp += inString[i];
temp += temp2;
temp += ")";
postToIn.push(temp);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.