Tag Archives: to_string

C++ || Snippet – Custom Template “ToString” Function For Primitive Data Types

The following is a custom template “ToString” function which converts the value of a primitive data type (i.e: int, double, long, unsigned, char, etc.) to an std::string. So for example, if you wanted to convert an integer value to an std::string, the following function can do that for you.

This function works by accepting a primitive datatype as a function parameter, then using the std::stringstream class to convert and return an std::string object containing the representation of that incoming function parameter as a sequence of characters.

The code demonstrated on this page is different from the std::to_string function in that this implementation does not require a compiler to have >= C++11 support. This function should work on any compiler.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output


-1987, 7.28, 12345678910, k, This is a c-string, This is a std::string