user2766546 user2766546 - 1 year ago 141
C++ Question

Checking input value is 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.


#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;


Answer Source

You can check like this:

int x;
cin >> x;

if ( {
    //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::cout << "Error" << std::endl;
        std::cin >> x;
    std::cout << x << std::endl;

    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download