1
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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
lch
  • 4,569
  • 13
  • 42
  • 75

3 Answers3

11

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).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
3
 words[i] = "word" + to_string(i+1);

Please look at this link for more detail about to_string()

Shravan40
  • 8,922
  • 6
  • 28
  • 48
1

I prefer the following way:

  string words[5];
  for (int i = 0; i < 5; ++i) 
  {
      stringstream ss;
      ss << "word" << i+1;
      words[i] = ss.str();
  }
VolAnd
  • 6,367
  • 3
  • 25
  • 43