C++ 从堆栈读取 char 到字符串结果为 "Unrecognized enum"

标签 c++ char stdstring

我是 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 填充的是“无法识别的枚举”,而不是 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"

在从运算符堆栈附加的位置上,有“自己的枚举”,而不是实际保存在那里的内容。

最佳答案

停止做 ""+ something!

这是 C++,它不会神奇地从字符串文字中生成字符串对象。

如果上面的代码真的编译了,这意味着 somethign 是某种整数类型,你正在获取 ""指向的位置的堆栈指针 (const char*) 并添加一个指针抵消那个。在下一个 NULL 之前,您不会读取一些随机数据

如果您想将某些内容转换为字符串,则需要对其进行转换。标准方法是通过输出流运算符。

enum OP
{
    OP_ADD,
    OP_SUB,
    OP_DIV,
    OP_MUL
};

std::ostream& operator << (std::ostream& os, OP op)
{
    switch (op)
    {
        case OP_ADD:
            os << "ADD";
            break;
        case OP_SUB:
            os << "SUB";
            break;
        case OP_DIV:
            os << "DIV";
            break;
        case OP_MUL:
            os << "MUL";
            break;
        default:
            throw std::logic_error("Invalid OP");
    }
}

然后可以这样使用:

OP op = OP_ADD;
std::stringstream buff;
buff << op;
std::string sop = buff.str();

但由于上面的代码很愚蠢,我有一个对象到字符串转换的简写:

template <typename T>
std::string to_string(T value)
{
    std::stringstream buff;
    buff << value;
    return buff.str();
}

然后可以这样使用:

OP op = OP_ADD;
std::string sop = to_string(op);

关于C++ 从堆栈读取 char 到字符串结果为 "Unrecognized enum",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47662605/

相关文章:

c++ - 返回字符串及其 .c_str() 的生命周期

c++ - 跨 DLL 边界的安全字符串复制

c++ - 在不知道宏数量的情况下打印宏值

c++ - 为什么我需要传递一个比较器来构造一个 priority_queue,当它是 lambda 时,而不是当它是 std::greater 时?

c++ - 用 C++ 编写依赖于文件系统的代码

c++ - 在C++中将字符串输入到动态分配的char内存中

powershell - Powershell,无法输入带有某些非ASCII字符的哈希表键(在脚本中)

c - 我是 C 的新手,有人可以解释为什么这个字符串的大小可以改变吗?

c++ - 在 C++ 中反转字符串

c++ - 从接口(interface)和实现 C++ 继承