mlimber,
I tried compiling the same program with a later ver of MS C/C++
compiler, which is ...
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42
for 80x86
With this compiler the test program gives expected results. But the GCC
compiler that I am using is gcc version 3.3.1 (mingw special
20030804-1), and it still gives out garbage. And by the way I believe,
there is no garbage i/p in the test program and hence there is no
question of GIGO.
I used g++ 3.4.4 (cygming special) to build and run this program:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdlib>
using namespace std;
class MyException {};
template<class T>
T value(const string& s)
{
istringstream is(s);
T val;
if( !(is >> val) || !(is >> ws).eof() )
{
throw MyException();
}
return val;
}
int main()
{
cout << "atof(2.22507e-308) -> "
<< atof("2.22507e-308") << '\n';
try
{
cout << "value<double>(2.22507e-308) ->"
<< value<double>("2.22507e-308");
}
catch( ... )
{
cout << "Caught exception.";
}
cout << endl;
}
It gives me the expected result. If it does not for you, then it is
likely a compiler/library problem, which you should ask about on
gnu.g++.help or similar.
Moreover, I don't think there is any need of
exception handling in the test code with the given valid input and I
don't understand how that extra piece of error checking will help. If
your compiler/lib gives you expected results with the given input, it
should behave the same without that as well.
Lastly I tried your changes with GCC and it generates exception and
that tells me that there is some definite issue in the related version
of c++ lib that it is using.
The exception handling is an alternate way of handling unexpected
errors to checking return values (cf.
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.1). In
this case, exceptions provide a way to indicate a failure without
having some sort of potentially invalid value (e.g., return FLOAT_MIN
on error or a std:
air<float,bool> where the flag indicates validity)
being returned to the client, and the client can catch and handle such
an error at whatever level is appropriate. Anyway, the fact that you
get an exception seems to indicate that there was in fact an unexpected
error of some kind, so I think your claim that this sort of error
checking is unnecessary is self-defeating.
Cheers! --M