该程序应检查输入的数字是否为整数。它适用于字符串,但不适用于 double 。
int test;
cout << "Enter the number:" << endl;
while(true) {
cin >> test;
if (!cin || test < 0) {
cout << "Wrong input, enter the number again:" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
最佳答案
test
是 int
。 istream >> 运算符只是动态转换为 int,然后,您将丢失小数部分。
您可以将 test
定义为 float
并在需要时将其转换为 int
。
编辑:回答您上次编辑(我没有刷新,所以我错过了这部分),发生的情况是,如果没有 goto
,您将循环两次:
- 您输入 1.5
test
为 1,且未输入 if,因此cin
未清理。- 再次循环,
cin
立即返回。 test
为 0,因此输入 if 语句并进行提示。
希望这有帮助
关于c++ - while 循环中的 cin 无法正常工作 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19979147/