c++ - C++ 中的字符串和整数连接

标签 c++ string int concatenation stdstring

<分区>

string words[5];
for (int i = 0; i < 5; ++i) {
    words[i] = "word" + i;
}

for (int i = 0; i < 5; ++i) {
    cout<<words[i]<<endl;
}

我期望的结果是:

word1
.
.
word5

但是它在控制台中是这样打印的:

word
ord
rd
d

谁能告诉我这是什么原因。我确信在 Java 中它会按预期打印。

最佳答案

C++ 不是 Java。

在 C++ 中,"word"+ i 是指针运算,不是字符串连接。请注意 string literal 的类型"word"const char[5](包括空字符'\0'),则衰减为const char* 这里。因此,对于 "word"+ 0,您将获得一个类型为 const char* 的指针,指向第一个字符(即 w),对于"word"+ 1 你会得到指向第二个字符的指针(即 o),依此类推。

你可以使用 operator+使用 std::stringstd::to_string (C++11 起)在这里。

words[i] = "word" + std::to_string(i);

顺便说一句:如果你想要 word1 ~ word5,你应该使用 std::to_string(i + 1) 而不是 std::to_string(i).

关于c++ - C++ 中的字符串和整数连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39198251/

相关文章:

C++ 禁用 C1061 错误 - block 嵌套到很深?

C++ 编译错误 : array has incomplete element type 'int []'

c++ - 使用 opencv : VideoCapture 内存泄漏

string - 打印可以由两个字符串组成的字符串

c++ - 为什么在 64 位机器上的 C++ 中 int 的大小不是 8 个字节。还有 gcc 的任何版本都支持 8 字节 int 吗?

c++ - 同时替换多个字符

c++ - LNK4217 关于派生自抽象 DLL 接口(interface)类的类的警告

Javascript - 替换特殊字符之间的文本

string - 如何找到至少重复一次的字符串中的最大序列?

c - 硬件帮助今晚到期。 Char To Int(帮助返回 Null)