Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-numeric input check

Tags:

c++

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. :)

like image 868
c0nn3ct Avatar asked Oct 07 '19 16:10

c0nn3ct


People also ask

How do you check if input is not number?

Use the isnumeric() Method to Check if the Input Is an Integer or Not. The isnumeric() method of the string returns True if the string only contains numbers. However, it is worth noting that it fails with negative values.

What does non-numeric result mean?

For example the laboratory result might be intended to be numeric but for very small values it would be resulted as “<2”. The symbol makes it a non-numeric result. For vital signs height might be 63 or sometimes entered as 5'3''. Again the symbols in the latter observation make the result non-numeric.

What is a non-numeric type of data?

Nonnumeric data types are data that cannot be manipulated mathematically using. standard arithmetic operators. The non-numeric data comprises text or string data. types, the Date data types, the Boolean data types that store only two values (true or.

What is a non-numeric?

Definition of nonnumerical : not relating to, involving, or consisting of numbers : not numerical nonnumerical clerical errors nonnumerical data.


1 Answers

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.

like image 72
R Sahu Avatar answered Oct 05 '22 23:10

R Sahu