1// to_string example
2#include <iostream> // std::cout
3#include <string> // std::string, std::to_string
4
5int main ()
6{
7 std::string pi = "pi is " + std::to_string(3.1415926);
8 std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
9 std::cout << pi << '\n';
10 std::cout << perfect << '\n';
11 return 0;
12}
1- Writing your own conversion function, the simple:
2template<class T> string toString(const T& x) {
3 ostringstream ss;
4 ss << x;
5 return ss.str();
6}
7- Since C++11 you can also use the std::to_string:
8 string s = to_string(0x12f3); // after this the string s contains "4851"
1#include <iostream>
2#include <boost/lexical_cast.hpp>
3using namespace std;
4int main()
5{
6 int i=11;
7 string str = boost::lexical_cast<string>(i);
8cout<<"string value of integer i is :"<<str<<"\n";
9
10}