J
James Kanze
[...]
On the other hand, his code will still hang, waiting for more
input, if the user enters an empty line instead of a number.
The usual solution when the input is line oriented is to use
getline systematically, then use istringstream if conversions
are needed. Something like:
std::cout << "Enter number: " ;
std::string line ;
getline( std::cin, line ) ;
std::istringstream parser( line ) ;
parser >> number >> std::ws ;
if ( ! parser || parser.get() != EOF ) {
std::cout << "Hey, that wasn't a number"
<< "(or there was extra garbage at the end)" <<
std::endl ;
// ...
}
// ...
cin.get();
after the cin>>number will do that. However, if there are any non-numeric
characters (such as spaces) after the number entered, the problem recurs
(ok, so it's user error, but...).
Maybe a more robust solution is:
getline(cin, garbage);
after the cin>>number, to eat any trailing garbage...
On the other hand, his code will still hang, waiting for more
input, if the user enters an empty line instead of a number.
The usual solution when the input is line oriented is to use
getline systematically, then use istringstream if conversions
are needed. Something like:
std::cout << "Enter number: " ;
std::string line ;
getline( std::cin, line ) ;
std::istringstream parser( line ) ;
parser >> number >> std::ws ;
if ( ! parser || parser.get() != EOF ) {
std::cout << "Hey, that wasn't a number"
<< "(or there was extra garbage at the end)" <<
std::endl ;
// ...
}
// ...