Horje
How to Use cin.fail() Method in C++?

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.

C++ cin.fail() Function

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.

Syntax to Use cin.fail() Method

if (cin.fail()) {
// The last input operation failed
}
else {
// The last input operation succeeded
}

C++ Program to Use cin.fail() Method

The below example demonstrates how to use the cin.fail() method in C++.

C++
// C++ program to use cin.fail() method

#include <iostream>
#include <limits>
using namespace std;

int main()
{
    // Declare and initialize integer variables.
    int i = 0, j = 0;

    // Infinite loop to continually ask for input until a
    // valid integer is entered.
    while (true) {
        // Ask the user to enter int value.
        cout << "Enter an Integer: " << endl;

        i++;

        // Read input from the user.
        cin >> j;

        // Check if the input operation failed (i.e., input
        // was not an integer).
        if (cin.fail()) {
            // Clear the error flags on the input stream.
            cin.clear();

            // leave the rest of the line
            cin.ignore(numeric_limits<streamsize>::max(),
                       '\n');

            // Ask the user to enter a valid int number only
            cout << "Wrong input, please enter a number: ";
        }
        else {
            // Print the valid integer entered by the user.
            cout << "Integer " << i << ": " << j << endl;
        }
    }
    return 0;
}


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)






Reffered: https://www.geeksforgeeks.org


C++

Related
How to Read File into String in C++? How to Read File into String in C++?
How to Access Private Variable in C++? How to Access Private Variable in C++?
How to Add Multiple Conditions for if Statement in C++? How to Add Multiple Conditions for if Statement in C++?
C++ Program to Implement Adjacency Matrix C++ Program to Implement Adjacency Matrix
How to Use the std::mutex Synchronization Primitive in C++ How to Use the std::mutex Synchronization Primitive in C++

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18