![]() |
VOOZH | about |
In C++, the cin.fail() method is a part of <iostream> library that is used to check whether the previous input operation has succeeded or not by validating the user input. In this article, we will learn how to use cin.fail() method in C++.
Example:
Input:
Enter an integer: a
Output:
Invalid Input. Please Enter an Integer.
We can use the cin.fail() method to check if the last input operation was successful or not. This function returns true if the last cin command failed and false otherwise. So, it can be used to validate user input and ensure that it meets certain criteria.
if (cin.fail()) {
// The last input operation failed
}
else {
// The last input operation succeeded
}
The below example demonstrates how to use the cin.fail() method in C++.
Output
Enter an Integer:
5
Integer 1: 5
Enter an Integer:
M
Wrong input, please enter a number: Enter an Integer:
4
Integer 3: 4
....
Time Complexity: O(1)
Auxiliary Space: O(1)