【发布时间】:2018-05-19 15:28:13
【问题描述】:
我是 C++ 新手,一定有一些我遗漏的东西。我的代码是这样的:
std::stack<char> operators;
std::stringstream stream;
stream.str("5.2 + 3");
while(stream.peek() != -1){
char token = static_cast<char>(stream.get());
//some code checking if the token is valid
operators.push(token);
auto tmp = operators.top(); //there I can still see the char (for example '+')
std::string tmpStr = "" + tmp; //But when put into string, there is "Unrecognized enum"
}
变量 tmpStr 填充的是“Unrecognized enum”,而不是 tmp 的内容。
我找不到任何解决方案,但我相信它一定很简单。 感谢您的帮助。
编辑: 因此,如果我使用 tmpStr.push_back(tmp) 它可以工作。但后来我像这样使用它:
std::queue<std::string> outQueue;
outQueue.push(" " + operators.top());
//some code
std::string result = "";
while(!outQueue.empty()){
result.append(outQueue.front() + " ");
outQueue.pop();
}
//result then has for example something like "5.2 own enum 3 own enum"
在从 operators 堆栈附加的位置上,有“自己的枚举”,而不是实际保存在那里的内容。
【问题讨论】:
-
"" + tmp实际上将偏移量应用于指针,它不会将字符“添加”到空字符串中。如果你想将字符添加到字符串中,那么你需要调用tmpStr.push_back(tmp);。 -
这行得通,谢谢。但是如果我将 tmpStr 添加到另一个字符串,它会导致与运算符 += 相同的问题,即使我使用 append() 也是如此。是不是也有什么特殊的方法呢?
-
将 tmpStr 添加到其他字符串或字符串文字应该没问题,因为有重载的
operator +来处理这些情况。您应该提供一些代码来演示这个新问题。 -
从单个
char构造tmpStr的其他方法是std::string tmpStr(1, tmp);和std::string tmpStr(&tmp, 1); -
我已经编辑了帖子,所以您可以看到新问题。哪里有
" " + operators.top()我尝试使用 push_back 方法使用临时字符串变量,然后插入,但这也没有帮助。