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
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);
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)
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.
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.
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;
Sorry about that. It was part of the proposals for TR2.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1973.html