-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);
0

1 Answer 1

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";
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.