Lokesh Cherukuri Lokesh Cherukuri - 3 months ago 11
C++ Question

string and int concatenation in 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;
}


I expected result as :

word1
.
.
word5


Bu it printed like this in console:

word
ord
rd
d


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

Answer

C++ is not Java.

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.

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

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

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

Comments