Bob Hairgrove wrote:[color=blue]
> On 6 Dec 2005 02:31:00 -0800,
deane_gavin@hotmail.com wrote:
>[color=green]
> >
> >Trond Valen wrote:[color=darkred]
> >> Hi!
> >>
> >> Stupid atof, it returns 0.0 when it tries to parse something like
> >> "fish". So I don't know whether the number was really 0 or a string that
> >> couldn't be parsed. Is there a better way to do this?[/color]
> >
> >Stupid indeed. But to answer your question: yes, there is a better way.
> >Use C++ stringstreams from <sstream>[/color]
>
> It isn't quite that easy. For example, what does this program do? You
> might expect it to throw an exception, but it doesn't:[/color]
Why would I expect that? Apart from memory allocation, where is any
code that might throw?
[color=blue]
> #include <iostream>
> #include <ostream>
> #include <sstream>
> #include <string>
>
> int main() {
> using namespace std;
> istringstream ss(string("fish"));
> double f = 0.0;
> ss >> f;
> cout << f << endl;
> }[/color]
Implicit in my statement that you can use streams is the requirement
that you know (or learn) *how* to use them. What your code is missing
is an important part of using any input stream (including, for example,
std::cin). That is, *every* time you read something, you should check
the stream state to see if it succeeded. So after ss >> f; you need
something like
if (!ss)
{
// failed to read a double
// report the error, perhaps by throwing an exception
}
[color=blue][color=green]
> >or use strtod (and strtol instead
> >of atoi) which can distinguish between zero and an error case.[/color]
>
> This is much better IMHO.[/color]
For simple cases (like the OP's) it is perfectly sufficient.
Gavin Deane