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.

2
  • C++ is not Java. What you're looking for is the to_string function. Commented Aug 29, 2016 at 3:55
  • This answer has a C++11 solution as well as older solutions. Commented Aug 29, 2016 at 3:55

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

It is to_string(i + 1) not just i
@YuanWen Thanks for reminding.
When using Arduino simple cast to String can be used: words[i] = "word" + (String)i;
3
 words[i] = "word" + to_string(i+1);

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

Comments

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();
  }

2 Comments

Why ? For efficiency or clarity or anything else?
I suppose, for efficiency. But in this example, when only one + to make each line, I think it is not so important.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.