Reputation: 111
I was wondering how I could convert an int to a string and then add it to an existin string. i.e.
std::string s = "Hello";
//convert 1 to string here
//add the string 1 to s
I hope I'm making sense. Thank you very much in advance for any answer.
Upvotes: 1
Views: 59
Reputation: 234665
The "modern" way is to use std::to_string(1)
. In fact, various overloads of std::to_string
exist for different number types.
Putting this together you can write std::string s = "Hello" + std::to_string(1);
Alternatively you can use std::stringstream
which can be faster due to fewer string concatenation operations which can be expensive:
std::stringstream s;
s << "Hello" << 1;
// s.str() extracts the string
Upvotes: 2
Reputation: 409166
If the number you want to append is an integer or floating point variable, then use std::to_string
and simply "add" it:
int some_number = 123;
std::string some_string = "foo";
some_string += std::to_string(some_number);
std::cout << some_string << '\n';
Should output
foo123
Upvotes: 3