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
  • 163,662
  • 15
  • 289
  • 382
lch
  • 3,901
  • 11
  • 35
  • 71

3 Answers3

10

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
  • 163,662
  • 15
  • 289
  • 382
3
 words[i] = "word" + to_string(i+1);

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

Shravan40
  • 7,746
  • 5
  • 27
  • 45
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,210
  • 3
  • 20
  • 41