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. :)
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.
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.
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.
Definition of nonnumerical : not relating to, involving, or consisting of numbers : not numerical nonnumerical clerical errors nonnumerical data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With