[Solved] Integers and while loop in C++… how?


Depending on how you define and initialize x, it may go into the loop every time you enter a non-integer, or it may only go into the loop sometimes.

If you don’t assign any value to x, then the value of x is still undefined after cin >> x if you enter a non-integer, because conversion failed and therefore no value is written to x. So x could be literally any number, and you have undefined behavior in your program. It may enter the loop sometimes and other times it may not.

If you assign something like 0 to x initially, then the value of x will still be 0 if conversion fails, because it is not changed, and therefore the loop condition would be true and the loop would be entered.

One option would be to only loop if the conversion succeeded, which you could do like this:

int main(void) {
    while ((cin >> x) && x != 1 && x != 2 && x != 3) {
        cout << "Invalid input, try again!" << endl;
    }
    cout << "Hello, World";
    return 0;
}

cin >> x will return cin, which evaluates to false in boolean context if an error condition was encountered (EOF, failed conversion, etc.).

0

solved Integers and while loop in C++… how?