user2766546 user2766546 - 8 months ago 52
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;



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;