Search code examples
c++cin

Checking cin input stream produces an integer


I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.

How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.

Thanks

 #include <iostream>
using namespace std;

int main ()
{

    int firstvariable;
    int secondvariable;
    float float1;
    float float2;

    cout << "Please enter two integers and then press Enter:" << endl;
    cin >> firstvariable;
    cin >> secondvariable;

    cout << "Time for some simple mathematical operations:\n" << endl;

    cout << "The sum:\n " << firstvariable << "+" << secondvariable 
        <<"="<< firstvariable + secondvariable << "\n " << endl;

}

Solution

  • You can check like this:

    int x;
    cin >> x;
    
    if (cin.fail()) {
        //Not an int.
    }
    

    Furthermore, you can continue to get input until you get an int via:

    #include <iostream>
    
    
    
    int main() {
    
        int x;
        std::cin >> x;
        while(std::cin.fail()) {
            std::cout << "Error" << std::endl;
            std::cin.clear();
            std::cin.ignore(256,'\n');
            std::cin >> x;
        }
        std::cout << x << std::endl;
    
        return 0;
    }
    

    EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).

    #include <iostream>
    #include <string>
    
    int main() {
    
        std::string theInput;
        int inputAsInt;
    
        std::getline(std::cin, theInput);
    
        while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
    
            std::cout << "Error" << std::endl;
    
            if( theInput.find_first_not_of("0123456789") == std::string::npos) {
                std::cin.clear();
                std::cin.ignore(256,'\n');
            }
    
            std::getline(std::cin, theInput);
        }
    
        std::string::size_type st;
        inputAsInt = std::stoi(theInput,&st);
        std::cout << inputAsInt << std::endl;
        return 0;
    }