c0nn3ct
c0nn3ct

Reputation: 61

Non-numeric input check

I have a piece of code here:

int a,b;
cout << "Enter your parameters a and b." << endl;
while(!(cin >> a >> b) || cin.get() != '\n')
{
cout << "Error. One of your parameters isn't a number. Please, input correct values." << endl;
cin.clear();
while(cin.get() != '\n');
}

I know this is a non-numeric input check, but I don't know how it works. Can someone tell me how it works? May be I do not understand how flow works and this is the reason of my misunderstanding of this piece of code. :)

Upvotes: 5

Views: 525

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Use of

while(!(cin >> a >> b) || cin.get() != '\n')

is a bit over zealous. If your input contains whitespace characters after the numeric input, it is going to fail. Ideally, you would like it to work if the input is "10 20 " or just "10 20". It could be

while(!(cin >> a >> b))

That quibble aside, if extraction into a or b fails, the stream, in this case cin, is left in an error state. After that, the line

cin.clear();

clears the error state but it still leaves the input in the stream. The line

while(cin.get() != '\n');

reads and discards the input until the newline character is encountered. After that your code is ready to read fresh input and cin is in a good state to process the input.

Upvotes: 6

Related Questions