Float-to-string conversion that raises exception instead of returning0.0 like atof

J

Jacek Dziedzic

Perhaps we can clarify the eof() and fail() issue?
I propose the code I've been using with success for
some time. I *think* it is correct as it had never
failed me, but perhaps I'm missing something and it's
not portable or something. Please comment.

double str_to_double(std::string s) {
stringstream ss(s);
double i;
ss >> i;

// when the conversion goes fine:
// - the stream is eof(), because all chars were read
// - because of eof() it is also !good(),
// - fail(), however, is 0 (sic!)
// good: 0, fail: 0, eof: 1, !ss==fail==0

// when the conversion goes wrong
// 1) some chars could not be converted as in "foo"
// - stream is in fail state
// - good: 0, fail: 1, eof: any, !ss==fail==1
// 2) conversion was fine, but chars remain in the
// stream, which means the text was something
// more than a number, as in "234.aaa" or "1.2.3"
// then stream is good() and !eof() (chars remain)
// - good:1, fail: 0, eof: 0, !ss==fail==0
// 3) trying to convert a "" (empty string)
// - stream ran out of characters and is in eof and fail
// - good:0, fail: 1, eof: 1, !ss==fail==1

// summary: a conversion is deemed successful when
// !good() and !fail() (sic!)

if(!ss.good() && !ss.fail()) return i;
throw EConversionError("Offending string: "+s); // defined elsewhere
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top