|
| | >
| >
Hi Chris.
| > | template<typename T>
| > | T FromString( const std::string& s )
| > | {
| > | std::istringstream is(s);
| > | T t;
| > | is >> t;
| > | if( !is ) {
| > | // do whatever you like to do, in case the conversion was not
| successful
| >
| > [snip]
| >
| > The above won't catch an un-successful conversion.
|
| Well, it does on the implementations I've come across so far. Why do you
| think it does not? An un-successful conversion sets the failbit which is
| tested for by operator! for the ios_base class.
Note, I said it won't catch an *un-successful* conversion.
Maybe you misunderstood my intentions, of which I'll try to
demonstrate below with some code.
| > I think you wanted:
| >
| > if( !is.eof() )
| > {
| > // ...
| >
|
| Which is also a way to go. However, I don't see why the usual test for the
| stream state shouldn't work. If you could shed some light on this I'd be
| happy.
Sure, hopefully the following will explain what I'm getting at.
template<typename T, typename U>
T FromString( const U& s )
{
std::istringstream is(s);
T t;
is >> t;
if( !is ) {
std::cout << "Error: Could not parse token " << std::flush;
}
return t;
}
int main()
{
// Note the character 'x'...
std::cout << FromString<int>( "12x34" ) << std::endl;
return 0;
}
I have modified the template function slightly to handle
the std::string class, but the above will indicate successful
conversion, and the message will not be output, resulting in
the integer '12' being output - not what we wanted.
Try the above using '.eof()', which will catch the error, if we
did not successfully read to the end of the token.
Cheers.
Chris Val
PS: It would be preferable to use both checks, and I'm sure you
understand this
.