Open In App

How to Output Error When Input Isn’t a Number in C++?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, when taking user input, we may need to validate that it is a number and output an error if it is not. In this article, we will learn how to output an error when the input isn’t a number in C++.

For Example,

Input:
Enter a Number: G

Output:
Error: That was not a number.

Output Error When Input Isn’t a Number in C++

The std::cin automatically deduces the type of data that is to be extracted from the input and puts it into the specified variable. We can use the (!) NOT operator with cin which is overloaded to check the state of the cin. The state of std::cin is set to bad when the input data type does not match the variable type. We can use this property to check whether the given data is a number or not.

Approach

To output an error when the input entered by the user is not a number do the following:

  • First, try to read the input using std::cin and check for input failure.
  • If an error is detected, use std::cin.clear() to clear the error state, and std::cin.ignore() to ignore the rest of the input line.
  • Finally, output an error message if an error is detected.

C++ Program to Output Error When Input isn’t Number

The below example demonstrates how we can check and output an error when the input isn’t a number in C++.

C++




// C++ program to Output Error When Input Isn't a Number
  
#include <iostream>
#include <limits>
using namespace std;
  
int main()
{
    // Prompt the user to enter a number
    cout << "Please enter a number: ";
  
    int num;
  
    // Keep reading input until a valid number is entered
    while (!(cin >> num)) {
        // Clear the error state
        cin.clear();
  
        // Ignore the rest of the incorrect input
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
  
        // Prompt the user again
        cerr << "Error: That was not a number. Please "
                "enter a number: ";
    }
  
    // Output the entered number
    cout << "You entered the number: " << num << endl;
  
    return 0;
}


Output:

Please enter a number: g
Error: That was not a number. Please enter a number: 5
You entered the number: 5

Time Complexity: O(1)
Space Complexity: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads