Concatenate an integer to a string object in C++
This post will discuss how to concatenate an integer to a string object in C++.
1. Using to_string() function
The most commonly used approach to concatenate an integer to a string object in C++ is to call the std::to_string function, which can return the string representation of the specified integer.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <string> int main() { int i = 17; std::string s = "C++" + std::to_string(i); std::cout << s << std::endl; return 0; } |
Output:
C++17
2. Using std::stringstream function
Another good alternative is to use the std::stringstream. The following C++ program demonstrates it:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> #include <string> #include <sstream> std::string toString(auto &i) { std::stringstream ss; ss << i; return ss.str(); } int main() { int i = 17; std::string s = "C++" + toString(i); std::cout << s << std::endl; return 0; } |
Output:
C++17
3. Using boost’s lexical_cast
We can also use a boost::lexical_cast<> to concatenate an integer to a string object, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> #include <boost/lexical_cast.hpp> int main() { int i = 17; std::string s = "C++" + boost::lexical_cast<std::string>(i); std::cout << s << std::endl; return 0; } |
Output:
C++17
That’s all about concatenating an integer to a string object in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)