string and int concatenation in C++ -
this question has answer here:
- how concatenate std::string , int? 26 answers
string words[5]; (int = 0; < 5; ++i) { words[i] = "word" + i; } (int = 0; < 5; ++i) { cout<<words[i]<<endl; }
i expected result :
word1 . . word5
bu printed in console:
word ord rd d
can tell me reason this. sure in java print expected.
c++ not java.
in c++, "word" + i
pointer arithmetic, it's not string concatenation. note type of string literal "word"
const char[5]
(including null character '\0'
), decay const char*
here. "word" + 0
you'll pointer of type const char*
pointing 1st char (i.e. w
), "word" + 1
you'll pointer pointing 2nd char (i.e. o
), , on.
you use operator+
std::string
, , std::to_string
(since c++11) here.
words[i] = "word" + std::to_string(i);
btw: if want word1
~ word5
, should use std::to_string(i + 1)
instead of std::to_string(i)
.
Comments
Post a Comment