【问题标题】:C++ reading char from stack to string results in "Unrecognized enum"C++ 将字符从堆栈读取到字符串导致“无法识别的枚举”
【发布时间】: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(&amp;tmp, 1);
  • 我已经编辑了帖子,所以您可以看到新问题。哪里有 " " + operators.top() 我尝试使用 push_back 方法使用临时字符串变量,然后插入,但这也没有帮助。

标签: c++ char stdstring


【解决方案1】:

别再做"" + 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# 之后很难习惯。
  • 当我看到 "" + 某些东西的那一刻,所有的警钟都响了...我在想 JavaScript,但是是的,C# 也是这样。
猜你喜欢
  • 1970-01-01
  • 2011-11-02
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多