| On Sat, 23 Oct 2004 19:34:38 +1000, "Chris \( Val \)"
[snip]
| >| int main()
| >| {
| >| using namespace std;
| >| int a;
| >| char const * pc = "1234567890";
| >| std::istringstream iss(pc);
| >| iss >> a;
| >| cout << "Number is: " << a << endl;
| >| return 0;
| >| }
| >
| >If you want that to work safely, then you'll need
| >to add some error checking, otherwise it too can
| >fail miserably.
|
| Hmm ... just tried a huge number. I thought that if the number
| represented by the string were too large, istream:
perator>> should
| throw an exception. But it doesn't!
That will only happen if you turn 'istream::exceptions()'
on manually, by setting the appropriate bit mask(s), but
it is not always ideal, and still requires further code
to make it safe, I think.
| Here's an improved version:
|
| #include <iostream>
| #include <ostream>
| #include <sstream>
| #include <stdexcept>
| #include <limits>
|
| int main()
| {
| using namespace std;
| try
| {
| int a;
| double d;
| char const * pc = "12345678901234567890";
| std::istringstream iss(pc);
| iss >> d;
| if (d <= numeric_limits<int>::max()
| && d >= numeric_limits<int>::min())
| {
| a = static_cast<int>(d);
| cout << "Number is: " << a << endl;
| }
| else
| {
| cout << "Error: number " << iss.str();
| cout << " is out of range for int." << endl;
| }
| }
| catch(const std::exception &e)
| {
| cout << "Error: " << e.what() << endl;
| }
| return 0;
| }
It's not that much safer than the original
If I change the number to represent:
char const * pc = "1.234";
....the result is '1', clearly incorrect.
It also does not accommodate for trailing white space,
where as the 'strto*' functions do.
You can check it for this, as well as eof() condition,
which should do the trick:
template<typename T>
inline T ConvertTo( const char* const Source )
{
T Value( 0 );
std::istringstream Iss( Source );
if( !( Iss >> Value >> std::ws && Iss.eof() ) )
{
throw std::runtime_error(
"ERROR: Could not convert source string. " );
}
return Value;
}
int main()
{
std::string N( "123" );
try
{
std::cout << ConvertTo<int>( N.c_str() ) << std::endl;
}
catch( const std::runtime_error& e )
{
std::cerr << e.what() << std::endl;
}
return 0;
}
Cheers.
Chris Val