-3

I am extremely new to programming and C++. My question is how do I check first the input is an integer and gives the invalid response if it's not. The code works if I input numbers but if I input a letter, it just goes into infinite loop. I've tried using the !cin but no success. Here's the bit part of where the problem is:

    do
    {
        if(Z < 0 || Z > 118 || !cin)
        {
            cout <<"You have entered an invalid value.\n";
        }
        cout <<"\nPlease enter the atomic number, Z:\n"; cin>>Z;  // Ask user to enter atomic number
    } 

    while (Z < 0 || Z > 118 || !cin);
Cubed
  • 35
  • 2
  • 7

1 Answers1

1

You can use the of the results of the expression cin >> z in the condition

int z;

while(cin >> z && (z < 0 || z > 118)) {
    cout <<"You have entered an invalid value.\n";
    cout <<"\nPlease enter the atomic number, Z:\n";
}
andre
  • 7,018
  • 4
  • 43
  • 75