|
||||
|
Section 39:
|
[39.1] How do I convert a value (a number, for example) to a std::string?
There are two easy ways to do this: you can use the <cstdio> facilities or the <iostream> library. In general, you should prefer the <iostream> library. The <iostream> library allows you to convert pretty much anything to a std::string using the following syntax (the example converts a double, but you could substitute pretty much anything that prints using the << operator):
// File: convert.h
#include <iostream>
#include <sstream>
#include <string>
#include <stdexcept>
class BadConversion : public std::runtime_error {
public:
BadConversion(std::string const& s)
: std::runtime_error(s)
{ }
};
inline std::string stringify(double x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion("stringify(double)");
return o.str();
}
The std::ostringstream object o offers formatting facilities just like
those for std::cout. You can use manipulators and format flags to control
the formatting of the result, just as you can for other std::cout.
In this example, we insert x into o via the overloaded insertion operator, <<. This invokes the iostream formatting facilities to convert x into a std::string. The if test makes sure the conversion works correctly — it should always succeed for built-in/intrinsic types, but the if test is good style. The expression o.str() returns the std::string that contains whatever has been inserted into stream o, in this case the string value of x. Here's how to use the stringify() function:
#include "convert.h"
void myCode()
{
double x = ...;
...
std::string s = "the value is " + stringify(x);
...
}
|
|||