Open In App

How to Handle Wrong Data Type Input in C++?

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, when we’re expecting a certain type of input but the user enters a different type then such input is called incorrect data input and it can cause issues like unexpected behavior, program failures, or inaccurate results. In this article, we will learn how to handle wrong data type input in C++.

Handling Wrong Data Type Input in C++

To handle wrong data type input, we can use a combination of std::cin.fail() and std::cin.clear(). The std::cin.fail() function returns true if the last input operation failed, and std::cin.clear() clears the error state of the cin object.

Approach:

By using the below approach we can ensure that the program continues to take the input from a user until a valid input is entered, handling any wrong data type entered by the user.

  • Take input from the user using std::cin and check for valid input using the std::cin.fail() function.
  • If the input is valid, set the flag variable valid input as true and exit the loop.
  • If the input is invalid, print an error message, and clear the error state flags of the input stream including the fail bit using the std::cin.clear() function.
  • Ignore remaining invalid bits in the input buffer using std::cin.ignore.
  • Repeat the above steps, until a valid input is provided by the user.

C++ Program to Handle Wrong Data Type Inputs

The below program demonstrates how we can handle wrong data type inputs in C++.

C++
// C++ Program to Handle Wrong Data Type Inputs

#include <iostream>
#include <limits>
using namespace std;
int main()
{
    int num;
    bool validInput = false;

    while (!validInput) {
        cout << "Enter an integer: ";
        cin >> num;

        // Check for type mismatch of the input
        if (cin.fail()) {
            cout << "Invalid input! Expected an integer."
                 << endl;
            // Clear the failbit and ignore the remaining
            // input
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),
                       '\n');
        }
        else {
            // Input is valid
            validInput = true;
        }
    }

    cout << "You entered: " << num << endl;

    return 0;
}


Output

Enter an integer: adsafds
Invalid input! Expected an integer.
Enter an integer: !@fsgg
Invalid input! Expected an integer.
Enter an integer: 123
You entered: 123

Time Complexity: O(N), where N is the maximum number of iterations to validate the input.
Auxiliary Space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads