[英]c++ stack stringstream function returns integer vs ASCII
#include <iostream>
#include <string>
#include <stack>
#include <sstream>
using namespace std;
stack<int>aStack;
stack<int>operand1;
stack<int>operand2;
stringstream postfix;
stringstream &postfixExp(string ch)
{
for(int i =0; i< ch.length(); i++)
{
if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
{
aStack.push(ch[i]);
}
else if(ch[i] == '+')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x + y;
aStack.push(result);
}
else if(ch[i] == '*')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x * y;
aStack.push(result);
}
}
postfix << aStack.top();
return postfix;
}
int main()
{
string postfix = "32+2*";
stringstream * result = &postfixExp(postfix);
cout << result-> str() ;
return 0;
}
嗨,有人知道我上面的代码有什么问题吗? 我的程序应返回后缀表示法的值。 我输入“ 32 + 2 *”作为后缀表示法,它应该返回10。显然出了点问题,它返回-86代替
我想错误来自此特定代码
else if(ch[i] == '*')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x * y;
aStack.push(result);
}
从那里,我显示了操作数2,它显示的是-43而不是7(来自上一个加法运算符“ 34+”的推导)
请让我知道哪一部分是错误的,为什么我的操作数2的值不为7。
谢谢
在将字符压入堆栈之前,将其转换为整数。 在我看来,您的编译器应该已经对此发出警告。 尝试提高警告级别。
aStack.push(ch[i]);
变
aStack.push(ch[i] - '0'); // '0' is 48
还要注意,您可以使用<cctype>
isdigit
,而不是手动将ch[i]
与每个数字进行比较。
if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
{
aStack.push(ch[i]);
}
应该是:
if(ch[i] == '1' || ch[i] == '2' || ch[i] == '3' || ch[i] == '4' || ch[i] == '5' || ch[i] == '6' || ch[i] == '7' || ch[i] == '8' || ch[i] == '9' || ch[i] == '0' )
{
aStack.push(ch[i] - '0');
}
摆脱其他- 48
损坏了。
问题如下
else if(ch[i] == '+')
{
operand1.push(aStack.top());
aStack.pop();
operand2.push(aStack.top());
aStack.pop();
int x = operand1.top() - 48;
int y = operand2.top() - 48;
int result = x + y;
aStack.push(result + 48);
}
这将使其变为10。您还需要更改第二个aStack.push(result)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.