There are certain instances in C++ programming when it is necessary to convert a certain data type to another; one such conversion is from an int
to a string
.
Let’s have a look at a few ways to convert an int
data type to a string
:
stringstream
classThe stringstream
class is used to perform input/output operations on string-based streams. The <<
and >>
operators are used to extract (<<
) data from and insert (>>
) data into the stream. Take a look at the example below:
#include <iostream>#include <sstream>using namespace std;int main() {int num = 100; // a variable of int data typestring str; // a variable of str data type// using the stringstream class to insert an int and// extract a stringstringstream ss;ss << num;ss >> str;cout << "The integer value is " << num << endl;cout << "The string representation of the integer is " << str << endl;}
to_string()
methodThe to_string()
method accepts a value of any basic data type and converts it into a string. Take a look at the example below:
#include <iostream>#include<string>using namespace std;int main() {int num = 100; // a variable of int data typestring str; // a variable of str data type// using to_string to convert an int into a stringstr = to_string(num);cout << "The integer value is " << num << endl;cout << "The string representation of the integer is " << str << endl;}
boost::lexical_cast
boost::lexical_cast
provides a cast operator which converts a numeric value to a string value. See the example below:
#include <iostream>#include <boost/lexical_cast.hpp>using namespace std;int main() {// a variable of int data typeint num = 100;// a variable of str data typestring str;// using boost::lexical_cast<string> to convert an int into a stringstr = boost::lexical_cast<string>(num);cout << "The integer value is " << num << endl;cout << "The string representation of the integer is " << str << endl;}
The
libboost-dev
package is required in order to use this cast.