C++字符串流函数无法正确返回
C++ stringstream function does not return correctly
#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"。
可能应该添加一些检查,以确保您不会像其他人提到的那样从空堆栈中弹出。
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- C 字符串返回字符串的整数/双精度/长整型值
- 如何从COM模块中的函数返回字符串数组?
- React Native (Android):无法通过 JNI 在 jobject 中返回字符串
- 我如何在函数 cpp 中返回字符串
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 格式化返回字符串C++
- 返回字符串vs通过引用传递字符串以更新值
- 如何在不使用 STL 的情况下从函数反转字符串后返回字符串C++?
- 使用 ctypes 从函数返回字符串C++会给出大的 int,而不是 char 指针
- 从 C++ 中的模板函数返回字符串和整数
- 返回字符串的散点回文计数
- C++重载字符串 [] 运算符以返回字符串和
- 返回字符串和不同向量数据类型的映射C++
- 字符串函数不返回字符串? C++
- 从函数返回字符串C++错误
- 如何在返回字符串的函数中不忽略void值
- 我想将字符串转换为 Json 格式并返回字符串向量作为答案
- C - 返回字符串时的分割故障
- 使用向量和字符串函数返回字符串