generic stringstream function in c++
Something i’ve found useful while programming in C++, is the use of std::stringstream to convert different datatypes to std::string. Fortunately, the process is the same for all types. That’s why a generic helper-function is preferable and will simplify the process considerably.
In order to use stringstreams, the library <sstream> has to be included. The following will create a reusable stringstream helper-function using templates.
template <typename T> std::string to_string(const T& value) {
std::stringstream os;
os << value;
return os.str();
}
The parameter contains the value that will be converted into a string, so you only have to assign a string to the function.
// assign a new string to the return value of to_string and show the contents
std::string str = to_string(5.12);
std::cout << str;
leave a comment