C ++中的字符串和整型串联 [英] string and int concatenation in C++

查看:54
本文介绍了C ++中的字符串和整型串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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中按预期方式打印.

Can someone tell me the reason for this. I am sure in java it will print as expected.

推荐答案

C ++不是Java.

C++ is not Java.

在C ++中,"word" + i 是指针运算,不是字符串连接.请注意,字符串文字的类型 "word" const char [5] (包括空字符'\ 0'),然后在此处衰减为 const char * .因此,对于"word" + 0 ,您将获得类型为 const char * 的指针,该指针指向第一个字符(即 w ),用于"word" + 1 ,您将获得指向第二个字符的指针(即 o ),依此类推.

In C++, "word" + i is pointer arithmetic, it's not string concatenation. Note that the type of string literal "word" is const char[5] (including the null character '\0'), then decay to const char* here. So for "word" + 0 you'll get a pointer of type const char* pointing to the 1st char (i.e. w), for "word" + 1 you'll get pointer pointing to the 2nd char (i.e. o), and so on.

您可以使用 operator + 使用 std :: string std:: to_string (自C ++ 11起).

You could use operator+ with std::string, and std::to_string (since C++11) here.

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

BTW:如果您想要 word1 word5 ,则应使用 std :: to_string(i + 1)而不是std :: to_string(i).

BTW: If you want word1 ~ word5, you should use std::to_string(i + 1) instead of std::to_string(i).

这篇关于C ++中的字符串和整型串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆