【问题标题】:C++ Error in converting int to stringC++ 将 int 转换为字符串时出错
【发布时间】:2013-11-21 16:26:17
【问题描述】:

当我尝试将 int 转换为字符串时,它会产生奇怪的结果,我不知道它来自哪里,这是一个代码 sn-p:

if (!ss.fail() && !ss.eof()) {
    ss.clear();

    string operand1 = "" + num1;
    string operand2 = "";
    getline(ss,operand2);   
    operand2 = trim(operand2);

    cout << num1 << endl << operand1 << endl;
    return expression_isvalid(operand1) && expression_isvalid(operand2) && operator_isvalid(c);

}

ss 是 stringstream,num1 是 int,而 c 是 char。

基本上输入是像“1 + 1”这样的表达式,num1 包含它在该表达式中找到的第一个 int(使用 ss >> num1)

我不明白的是这部分

string operand1 = "" + num1; // assume input is "1 + 1" so num1 contains the value 1
...
cout << num1 << endl << operand1 << endl; 

输出

1
exit

我不知道“exit”是从哪里来的,这个词会根据输入而变化,当我输入“3+1”时“exit”变成“it”,当我输入“13+”时变成“ye” 2"。

【问题讨论】:

  • 在标题中写probelm的问题? :)
  • 是的。还有溢出缓冲区和东西的问题。 (那个随机字符串似乎来自对我的无效记忆-> UB。)
  • 我不确定:您是想将输入 int 转换为字符串,还是创建获取字符串表达式并将值作为字符串返回的 calc?
  • "" + num1 --- 这确实 not 将整数转换为字符串(实际上它会导致未定义的行为,这就是您得到奇怪输出的原因)。您需要了解如何正确地将整数转换为字符串。您还有两个疯狂的猜测,之后您必须打开 C++ 手册并阅读。
  • num1 是一个int,您将其添加到const (&amp;char)[1] 的逻辑基地址中。您意识到这不是inttext 翻译附加到字符串的方式,对吧?您实际上是在 const char 缓冲区上进行指针数学运算。

标签: c++ string output


【解决方案1】:

我建议你使用std的strtoul函数。 Here你可以找到一个很好的文档。

一个例子可能是:

static unsigned long stringToInt(const string& str) {
  const char* cstr = str.c_str();
  char* endPtr = 0;
  return ::strtoul(cstr, &endPtr, 0);
}

【讨论】:

  • 或者你可以建议一些更像 C++ 的东西并完全避免使用 strtoul。
【解决方案2】:

您可以使用stringstream 转换string 中的各种类型。我通常使用以下模板来做到这一点:

template <typename T>
static std::string strfrom(T x)
{
    std::ostringstream stream;

    stream << x;

    return stream.str();
}

然后要将int i 转换为string i_str,只需:

i_str = strfrom<int>(i)

【讨论】:

    猜你喜欢
    • 2018-01-13
    • 1970-01-01
    • 2020-08-02
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多