In this article, we will learn about three different ways to convert an integer to a string in C++ i.e.
- Using to_string() function
- Using stingstream
- Using Boost’s lexical_cast() function.
Let’s discuss them one by one.
Convert int to string using to_string()
C++ provides a function std::to_string() for converting values of different types to string type. We can use this to convert an integer to string. For example,
#include <iostream> #include <string> int main() { int num = 234; // Convert int to string std::string num_str = std::to_string(num); std::cout<<num_str<<std::endl; return 0; }
Output:
234
We passed an integer to the to_string() function, and it converted the given int to a string and returned the string object. If you pass a negative integer to the to_string(), it will convert to a string with a minus symbol.
Convert int to string using stringstream in C++
C++ provides a class stringstream, which provides a stream-like functionality. We can insert different types of elements in stringstream and get a final string object from the stream. Check out this example,
#include <iostream> #include <string> #include<sstream> int main() { int num = 234; std::stringstream stream; // Add int to the stream stream<<num; std::string str; // Get string object from the stream stream>>str; std::cout<<str<<std::endl; return 0; }
Output:
Frequently Asked:
234
In the stringstream, we inserted an integer, and the stream converted the integer to string. Then, in the end, we requested a string object from the stream.
Convert integer to string using boost::lexical_cast()
The C++ boost library provides a template function for data type conversion. It helps to convert elements from one data type to another. We can use that to convert an integer to a string. For example,
#include <iostream> #include <string> #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; int main() { int num = 234; // Convert int to string using boost library string str = lexical_cast<string>(num); cout<<str<<endl; return 0; }
Output:
Pointers in C/C++ [Full Course]
234
Summary:
We learned about three different ways to convert an integer to a string in C++.