C++字符串流函数无法正确返回

C++ stringstream function does not return correctly

本文关键字:返回 字符串 函数 C++      更新时间:2023-10-16
    #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;
}

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

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

然后我正在考虑使用字符串流函数。不幸的是,我仍然不知道如何显示相应的结果

我想知道是否有人可以告诉我我的代码中的哪个部分是错误的,或者除了使用字符串流或堆栈之外,是否有更好的方法来显示函数的结果

多谢!

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

解释很简单,您逐个字符"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();
}

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

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