Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

fastest way to get a double from a string

0 views
Skip to first unread message

aaragon

unread,
Nov 29, 2009, 8:41:26 PM11/29/09
to
Hi everyone,

I know that to obtain a double from a string, you can use something
like the following (from the C++-FAQ):

template <typename T>
T stream_cast(std::string& s) {

T x;
static std::stringstream iss;
iss.clear();
iss.str(s);
iss>>x;
if (!iss) {
std::string err("*** ERROR *** ");
err += s + " cannot be converted to expected type with type id:\n";
err += typeid(x).name();
throw std::runtime_error(err);
}
return x;
}

However, there has to be a faster way to accomplish this, and to fall
back to this implementation if things don't go as expected. Is what
I'm thinking possible? Could I use a try/catch block on the <cstdlib>
function stof()?

Thank you all,

aa

Kenshin

unread,
Nov 30, 2009, 2:03:12 AM11/30/09
to

std::string str("1.2");
double val = boost::lexical_cast<double>(str);

lexical_cast will be part of C++0x, so the below will be valid soon:

std::string str("1.2");
double val = std::lexical_cast<double>(str);

Pete Becker

unread,
Nov 30, 2009, 8:59:35 AM11/30/09
to
Kenshin wrote:
>
> lexical_cast will be part of C++0x
>

It's not there now, and I don't know of any plans to add it.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of
"The Standard C++ Library Extensions: a Tutorial and Reference"
(www.petebecker.com/tr1book)

Juha Nieminen

unread,
Nov 30, 2009, 10:18:40 AM11/30/09
to
aaragon wrote:
> However, there has to be a faster way to accomplish this

const char *startPtr = s.c_str(), *endpPtr;
double x = std::strtod(startPtr, &endPtr);
if(endPtr == startPtr) { /* error */ }

It's much faster because strtod (most probably) parses the string
in-place, unlike std::istringstream, which probably copies the string
for itself.

aaragon

unread,
Nov 30, 2009, 10:43:32 AM11/30/09
to

Thank you for your answers. I tried lexical_cast, and it is actually
slower than the stream_cast function above. I will try the strtod.
Thanks again.

Johannes Schaub (litb)

unread,
Nov 30, 2009, 10:41:59 AM11/30/09
to
aaragon wrote:

strstream combines flexibility of c++ with the speed of strtod:

istrstream s(str.c_str());
double d; if(s >> d >> ws && ws.eof()) cout << "converted: " << d;

Kenshin

unread,
Dec 1, 2009, 3:15:41 AM12/1/09
to

Sorry about that. It was part of the proposals for TR2.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1973.html

0 new messages