newbie problem with cin and getline

J

James Kanze

[...]
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 ;
// ...
}
// ...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top