C ++ stringstream函数无法正确返回

时间:2013-09-23 19:36:56

标签: c++ pointers stack stringstream

    #include <iostream>
    #include <stack>
    #include <string>
    #include <sstream>

    using namespace std;

    stack<char> aStack;
    stringstream result;
    stack<char> operand1;
    stack<char> operand2;


    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]== '+')
        {
          operand2.push(aStack.top());
          aStack.pop();

          operand1.push(aStack.top());
          aStack.pop();

      result << ( operand1.top() + operand1.top());
    }

  }

  return result;
}

int main()
{
    string postfix = " 2+3";

    stringstream* answer = &postfixExp(postfix);
    cout << "Result = " << answer->str() << endl;;


  return 0;
}

大家好,有没有人知道我的代码有什么问题? 我没有看到编译器的任何错误消息。然而,当我运行它时会崩溃。

我很难显示我从函数中得到的结果。 我最初想要使用堆栈函数,但我想不出如何将值传递给main函数并显示它。

然后我想改用stringstream函数。不幸的是,我仍然不知道如何显示相应的结果

我想知道是否有人能告诉我我的代码中哪个部分出错了,或者是否有更好的方法来显示函数的结果而不是使用stringstream或stack

非常感谢!

2 个答案:

答案 0 :(得分:1)

正如已经指出的那样,当aStack.pop();容器为空时调用aStack会导致错误。这可能会产生 未定义的行为 (在这种情况下)您可以观察到应用程序崩溃。

解释很简单,您逐字符处理字符串"2+3"

for each character:
    if it is digit:
        push it to stack
    if it is '+':
        pop 2 elements

...那么一旦达到"2+3"符号,您认为'+'字符串会发生什么?


还要考虑重新设计:

stringstream result;

stringstream& postfixExp(string ch) {
    ...
    return result;
}

...您正在返回对全局变量的引用,这意味着您要么不应该返回任何内容,要么该变量不应该是全局变量。但更好的是,请考虑仅传递std::string个对象(在函数内部使用stringstream):

std::string postfixExp(const std::string& expression) {
    std::ostringstream resultStream;
    ...
    return result.str();
}

答案 1 :(得分:0)

后缀算术运算的测试输入应采用“23+”的形式,而不是“2 + 3”。

可能应该添加一些检查,以确保您不会像其他人提到的那样从空堆栈中弹出。