There are three ways of converting an integer into a string:
The stringstream class is a stream class defined in the
The following are the operators used to insert or extract the data:
Let's understand the concept of operators through an example.
Let's understand through an example.
#include <iostream> #include<sstream> using namespace std; int main() { int k; cout<<"Enter an integer value"; cin>>k; stringstream ss; ss<<k; string s; ss>>s; cout<<"\n"<<"An integer value is : "<<k<<"\n"; cout<<"String representation of an integer value is : "<<s; }
Output
In the above example, we created the k variable, and want to convert the value of k into a string value. We have used the stringstream class, which is used to convert the k integer value into a string value. We can also achieve in vice versa, i.e., conversion of string into an integer value is also possible through the use of stringstream class only.
Let's understand the concept of conversion of string into number through an example.
#include <iostream> #include<sstream> using namespace std; int main() { string number ="100"; stringstream ss; ss<<number; int i; ss>>i; cout<<"The value of the string is : "<<number<<"\n"; cout<<"Integer value of the string is : "<<i; }
Output
The to_string() method accepts a single integer and converts the integer value or other data type value into a string.
Let's understand through an example:
#include <iostream> #include<string> using namespace std; int main() { int i=11; float f=12.3; string str= to_string(i); string str1= to_string(f); cout<<"string value of integer i is :"<<str<<"\n"; cout<<"string value of f is : "<< str1; }
Output
The boost.lexical cast provides a cast operator, i.e., boost.lexical_cast which converts the string value into an integer value or other data type value vice versa.
Let's understand the conversion of integer into string through an example.
#include <iostream> #include <boost/lexical_cast.hpp> using namespace std; int main() { int i=11; string str = boost::lexical_cast<string>(i); cout<<"string value of integer i is :"<<str<<"\n"; }
Output
In the above example, we have converted the value of 'i' variable into a string value by using lexical_cast() function.
Let's understand the conversion of string into integer through an example.
#include <iostream> #include <boost/lexical_cast.hpp> using namespace std; int main() { string s="1234"; int k = boost::lexical_cast<int>(s); cout<<"Integer value of string s is : "<<k<<"\n"; }
Output
In the above example, we have converted the string value into an integer value by using lexical_cast() function.