Conversions using std::to_string and “from_string”

String conversions using stringstream

Stringstream can be used to get values from a string, by using stringstream as adaptor.

Stringstream also has the operator << for adding a string into its stream.

In case the conversion fails (trying to add “abc” into an int for example), the value of the int will not be changed, but the flags of the stream will, which we can interrogate to check the status.

When you fail the conversion, there’s something strange going on, since the stream needs to consume the invalid input field from the stream. Otherwise, it will try to read again from the value from the last iteration.

We can also use the eof flag to know when we’ve finished with the stream data.

std::to_string (C++11)

to_string is a templated function that transform any primitive into a string.

Converting from string back to primitives (C++11)

There are a few functions added (stof, stoi, stol, stoul, stoll, stoull, stod, stold) that allows conversion from string to primitives. In case the conversion fails, an exception is thrown.

Careful with the locale!

Both stringstream and to_string use std::locale which can change the point to comma. This can have other implication, for example when trying to use the data in a json (json requires point instead of comma).

We can create our custom locale and use it, or force it to use the default one.

You may also like...

Leave a Reply