c ++ stack stringstream函数返回整数与ASCII

时间:2013-09-24 03:01:24

标签: c++ pointers reference stack stringstream

#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。

谢谢

3 个答案:

答案 0 :(得分:2)

在将字符推送到堆栈之前将其转换为整数。在我看来,你的编译器应该警告过你。尝试调高警告级别。

aStack.push(ch[i]);

变为

aStack.push(ch[i] - '0'); // '0' is 48

另请注意,您可以使用isdigit中的<cctype>,而不是手动将ch[i]与每个数字进行比较。

答案 1 :(得分:2)

  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

答案 2 :(得分:0)

问题如下

  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(结果)。