📜  如何在 C++ 代码示例中拒绝字符串输入

📅  最后修改于: 2022-03-11 14:44:49.545000             🧑  作者: Mango

代码示例1
while( ! cin >> x){ //While cin failed to stream the data; Reads input then checks if cin has failed
//Alternative:
/*
cin >> x;
while(cin.fail()){
*/
   cin.clear(); //Reset the flags, so you can use cin again
   cin.ignore(100, '\n'); //Empty the buffer
   cout << "Please enter a number!\n";
/* If alternative is used:
   cin >> x; //Read input again
*/
}