I am implementing this:
double x;
ostringstream x_convert;
x_convert << x;
string x_str = x_convert.str();
It seems a bit superfluous. Is there a more elegant way?
I am implementing this:
double x;
ostringstream x_convert;
x_convert << x;
string x_str = x_convert.str();
It seems a bit superfluous. Is there a more elegant way?
What you have is the safest method (pre-C++11).
Alternatively, you could so something like:
double value = SOME_VALUE;
char buffer[100] = {};
sprintf(buffer, "%f", value);
std::string s = buffer;
Which is functionally equivalent to what std::to_string
does. You must be careful to have enough space allocated for buffer
, and (as you can see), you are still writing about 4 lines of code to do this conversion, so it is no more (nor less) elegant than the other methods.
If you are stuck in pre-C++11, you can implement your own to_string
by doing something like:
template<typename T>
std::string to_string(T t)
{
std::ostringstream oss;
oss << t;
return oss.str();
}
Which will work for any type that already has an overload for std::ostream& operator<<(std::ostream&, T&)
.
Without C++11 you may write your own to_string
function:
string to_string(double x) {
ostringstream x_convert;
x_convert << x;
return x_convert.str();
}
With C++11, as mentioned by others, use std::to_string
.
Without C++11, you are stuck with the code you've already written, or something along those lines. You can make the use of that code a bit more elegant (read: less typing) by constructing a device which does the string building for you:
class StringBuilder
{
public:
template <typename T> inline StringBuilder& operator<<(const T& t)
{
mStream << t;
return * this;
}
inline std::string get() const
{
return mStream.str();
}
inline operator std::string () const
{
return get();
}
private:
std::stringstream mStream;
};
Now you can:
double x;
string x_str = StringBuilder() << x;
But at the end of the day it's really just syntactic sugar for the same thing. There are similar devices in Boost -- I'd use those if you can.