更新时间:2023-11-26 11:03:34
尝试:
while (1) {
if (cin >> x) {
// valid number
break;
} else {
// not a valid number
cout << "Invalid Input! Please input a numerical value." << endl;
cin.clear();
while (cin.get() != '\n') ; // empty loop
}
}
这基本上清除错误状态,然后读取并丢弃在上一行输入的所有内容。
This basically clears the error state, then reads and discards everything that was entered on the previous line.