Ulrich
Tue May 29 06:46:54 CDT 2007
Ananya wrote:
> I would like to find a simple method for converting a double to a string,
> almost as simple as:
> string convertIntToString(int i)
> {
> stringstream ss;
> string str;
> ss << i;
> ss >> str;
> return str;
> }
> without having to specify how many digits the double number has after the
> decimal point.
#include <boost/lexical_cast.hpp>
string const str = boost::lexical_cast<string>(3.14);
BTW:
1. C++ knows function overloading, so you could have named your
function 'convertToString()' instead.
2. C++ knows templates, so you could have make it a template function as
well, but there you are already where boost::lexical_cast<> goes, with the
exception that you don't have the reverse way:
double const d = boost::lexical_cast<double>("3.14");
You can get Boost at
http://www.boost.org. It contains several, mostly
independent libraries, so don't be afraid of its size.
Uli