【问题标题】:Why when i add number to string it shows random text in c++?为什么当我将数字添加到字符串时,它会在 C++ 中显示随机文本?
【发布时间】:2016-11-03 12:18:45
【问题描述】:

当我尝试将文本添加到字符串时,我得到随机值。

代码:

#include <iostream>

using namespace std;

int main()
{
    cout << "333" + 4;
}

我收到一些随机文本,例如:↑←@

【问题讨论】:

标签: c++ string int


【解决方案1】:

"333"const char [4] 而不是 std::string,正如您所期望的(顺便说一下,operator+ 仍然没有 int)。加 4,您将 converting 移动到 const char *,然后将指针移动 4 * sizeof(char) 字节,使其指向包含垃圾的内存。

【讨论】:

    【解决方案2】:

    发生这种情况是因为它们是两种不同的类型,并且加法运算符无法按您预期的那样工作。

    如果您打算将字符串文字 "333" 与 int 值 4 连接,那么您应该简单地使用 count 如下:

    cout << "333" << 4; // outputs: 3334
    

    如果您想显示 sum,请使用 stoi() 函数将字符串转换为 int。

    cout << stoi("333") + 4;  // outputs: 337
    

    注意: 使用 stoi() 时:如果字符串还包含文字,则转换将从字符串的开头获取整数值,或者如果字符串以文字:

    cout << stoi("333ab3") + 4; // same as 333 + 4, ignoring the rest, starting a
    cout << stoi("aa333aa3") + 4; // raise error as "aa" can't be casted to int
    

    【讨论】:

    • 它们不是不兼容的,但是执行的操作是指针算术,而不是加法或连接。
    • OP 想要将文本添加到字符串,而不是数字到数字
    • @Quentin 它们不是不兼容的,没错,但即使这是一个合法的指针算术运算,你应该看到这不是提问者所期望的。所以我的意思是他们不适合获得预期的结果。只要结果不是预期的结果,您就可以确定他不想要指针算术(即使询问者也没有指定它)。所以,我的意思是你不能把狗和鸟结合起来得到飞机……答案更新了,谢谢指点。它可能误导了其他人,也许,因为我没有那么明确。
    【解决方案3】:

    当您想在文本中添加文本时,解决方案是使用适当的类型:

    cout << std::string( "333" ) + "4";
    

    对于 c++14 或更高版本:

    using namespace std::string_literals;
    cout << "333"s + "4"s;
    

    【讨论】:

      【解决方案4】:

      老实说,我不知道您通过将 int 添加到字符串来达到什么目的。如果要添加 333+4,则需要像这样将字符串解析为 int:

      编辑:错字 #包括

      using namespace std;
      
      int main()
      {
          cout << std::stoi("333") + 4;
      }
      

      【讨论】:

      • 除了可怕的using namespace std;,这不会编译。
      • 我的错,有错字:std::stoi("333")+4;
      猜你喜欢
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 2022-07-22
      • 1970-01-01
      • 2017-09-20
      • 1970-01-01
      • 2021-04-09
      • 2020-12-22
      相关资源
      最近更新 更多