Patrick’s development blog

generic stringstream function in c++

Posted in C++ by Patrick on February 9, 2008

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;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: