string and int concatenation in C++ [duplicate]

假装没事ソ 提交于 2021-02-17 06:41:06

问题


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.


回答1:


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




回答2:


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

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




回答3:


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


来源:https://stackoverflow.com/questions/39198251/string-and-int-concatenation-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!