Converting to std::string

suggest change

std::ostringstream can be used to convert any streamable type to a string representation, by inserting the object into a std::ostringstream object (with the stream insertion operator <<) and then converting the whole std::ostringstream to a std::string.

For int for instance:

#include <sstream>

int main()
{
    int val = 4;
    std::ostringstream str;
    str << val;
    std::string converted = str.str();
    return 0;
}

Writing your own conversion function, the simple:

template<class T>
std::string toString(const T& x)
{
  std::ostringstream ss;
  ss << x;
  return ss.str();
}

works but isn’t suitable for performance critical code.

User-defined classes may implement the stream insertion operator if desired:

std::ostream operator<<( std::ostream& out, const A& a )
{
    // write a string representation of a to out
    return out; 
}

Aside from streams, since C++11 you can also use the std::to_string (and std::to_wstring) function which is overloaded for all fundamental types and returns the string representation of its parameter.

std::string s = to_string(0x12f3);  // after this the string s contains "4851"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::string:
* Converting to std::string

Table Of Contents
8 Arrays
11 Loops
20 std::string
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype