如何在cin.fail()中求解循环
How to solve the loop in cin.fail()
知道为什么会发生这种情况?
样本运行
void askNQ(int &noq)
{
bool x = true;
while (x)
{
int i;
cout << "How many questions would you like(out of " << noq << ")?" << endl;
cin >> i;
if (cin.fail())
{
cin.clear();
cin.ignore();
cout << "Sorry, that is not valid." << endl;
x = true;
}
else if (i > noq)
{
cout << "Sorry, that is too many." << endl;
x = true;
}
else if (i <= 0)
{
cout << "Sorry, that is too less." << endl;
x= true;
}
}
}
cin.ignore();
实际上是呼叫cin.ignore(1, char_traits<char>::eof());
。
因此,您不会从任何剩余的新线中清理缓冲区。
以下内容应解决您的问题:
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
它清除了下一个新线字符,无论它在缓冲区中有多远(出于所有实际目的)。
您应该在命令行中输入数字,因为变量" i"是整数。
相关文章:
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 在 std::getline 和 std::cin 期间卡在循环中
- C++ cin.ignore() 跳过循环
- 而循环跳过 cin.getline() 对于 C 字符串
- 当输入在带有空格的单行中给出时,cin 如何在 while 循环中工作?
- :CIN 不断打印用户在每次循环后输入的内容
- 输入 ctrl + x 后如何再次 cin (cin<<x) 循环(cin 一个结构)
- cin语句在循环的第三次迭代中被跳过
- 在循环中使用 cin.get() 输入字符串
- C++向量:在循环中使用CIN初始化
- 当我输入一个字母时,cin 输入(输入是一个 int),而不是打印错误一次,它打印正确一次,然后在循环的其余部分打印 i
- 为什么cin.rdbuf()->sbumpc()在循环中只要求我输入一次?
- 在 for 循环中使用后,Cin 被跳过
- 如何在我的代码中修复无穷循环?我认为它跳过了第二个CIN,因此它一直在循环
- C :在(CIN)循环中,有时会忽略循环
- 如果 (!(cin >>变量名称)) 在此循环中
- CIN 到矢量输入循环无限期.为什么
- C++ if(cin>>input) 在 while 循环中无法正常工作
- std::cin 导致无限循环
- 我可以做一个循环,直到“std::cin”在输入缓冲区中看到“”字符