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

标签 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。

谢谢

最佳答案

  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,因为它们已损坏。

关于c++ stack stringstream函数返回整数与ASCII,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18972271/

相关文章:

perl - 在 Perl 中传递标量引用

c++ - C++11 中的委托(delegate)

C++ 使用 std::pair 模板特化定义树节点数据结构

java - C语言中如何让数组的第二行指向第一行

C++ : how is a reference to the value of a pointer is updated when the pointer itself changes?

reference - 为什么我可以返回对局部文字的引用而不是变量?

c++ - qt 将对象传递给不同的类

c++ - 为什么在 C++ 中使用 <cstdio> 而不是 <stdio.h> 时 "std::printf"和 "printf"都会编译?

c# - 将 C dll 和方法导入到 c# 中

无法转换为指针类型,转换结构