<分区>
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 中它会按预期打印。
<分区>
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::string
和 std::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/