0

This is my code:

#include <iostream>
int main(){
    int x;
    int y = 1;
    while(x != y){
        std::cout << "Please, enter 1." << std::endl;
        std::cin >> x;
        try{
            if(x != y){
            throw 2;
           }
        }
        catch(int){
            std::cout << "You didn't enter 1." << std::endl;
        }
    }
    if(x == 1){
        std::cout << "Well done." << std::endl;
    }
    return 0;
}

When I provide 1 as input, it works nicely, outputting the message "Well done" as intended. However, when I provide cin with any other kind of input, the code produces a loop that prints out the message "You didn't enter 1" indefinitely. I'd like to know why that's happening.

1 Answers1

1

After you give non integer value of x,

cin >> x

cin goes into error state and can not read further.. so loop continue as there is no stoppage except statement containing cin.

code707
  • 1,663
  • 1
  • 8
  • 20