C++ cin.fail() question
问题 When running the following code and enter a number, it works fine. But when entering a letter, the program enters an infinite loop, displaying "Enter a number (0 to exit): cin failed." My intent was to handle the cin fail case and prompt the user again. int number; do{ cout << "Enter a number (0 to exit): "; cin >> number; if(cin.fail()){ cout << "cin failed." << endl; cin.clear(); }else{ cout << "cin succeeded, " << number << " entered." << endl; } }while(number != 0); 回答1: You need to clear