I got a code, for avoidance of any signs input, despite "int" characters.
Please, explain me step by step what exactly is happening here?
1 2 3 4 5 6 7 8 9
while (!(cin >> x) || (cin.peek() != '\n') || x <= 0)
//
{
cin.clear();
//
while (cin.get() != '\n');
//
cout << "Error. Not a Natural number. Try one more time" << endl;
If it failed (the ! part) ...
... or if there was something left on the line before the new line ...
... or if x was non-positive ...
then it:
- cleared the stream of any errors;
- kept inputting characters up to and including the new line from the enter key;
- told you in no uncertain terms that you’d boobed.
It seems a bit obfuscatory, to be honest. But I expect I’ve written worse.
Note that || is a short-circuit logical operator. The terms are only evaluated left to right until one term evalutes to true or they have all been evaluated in which case the result is false.