How to check an input variable

Suppose we have a simple situation, like the following C++ instructions:

int x;

cout << "Insert x: ";
cin >> x;

while ( x-- < 0 ) ;

Of course, if it is written something different from an integer, the while loop shall not end.

So, how can we check if the input x is of the right type?

With the typeof function?

That's a builtin of gcc, not really a function - it can't really be used to "check" the type of a variable, just to mimic it's type. Even if it could, C++ is statically typed, so x will always be an int, no matter what the user enters.

cin has a function called fail() which returns true if the last read (in the current thread) couldn't parse the input correctly - you can use that to check what you want.

The while-loop will always end - try it. Even if "cin >> x" fails, x will still hold some value (though an undefined one) that the while-loop will eventually bring down to a value so low it underflows to a positive number.

1 Like