我正在尝试将一个简单的问题和数字检查器编码到我的第一个C ++程序中。 问题是,当我键入一个像两个或三个字符串的字符串时,程序变为无限循环,它忽略了cin函数,将生命重新分配给一个数字。
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;
while(lives != 1 && lives != 2 && lives != 3 && !isdigit(lives))
{
cout << "You need to input a number, not words." << endl;
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;
}
以下是我当前的代码及其建议:
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
std::cin.ignore();
std::cin.clear();
if (std::cin >> lives)
{
while(lives != 1 && lives != 2 && lives != 3)
{
cout << "You need to input a number, not words." << endl;
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;
}
}
答案 0 :(得分:9)
#include <iostream>
#include <limits>
int main()
{
int lives = 0;
std::cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << std::endl;
while(!(std::cin >> lives) || lives < 1 || lives > 3)
{
std::cout << "You need to input a number, not words." << std::endl;
std::cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return 0;
}
好的。 std::cin.clear();
负责重置失败位。 std::cin.ignore
删除流中剩余的任何错误输入。而且我已经调整了停止条件。 (isDigit
是一个冗余的检查,如果生命在1到3之间,那么显然它是一个数字)。
答案 1 :(得分:3)
当std::istream
无法读取值时,它会进入失败模式,即设置std::failbit
并且测试时流产生false
。您总是想测试读取操作是否成功:
if (std::cin >> value) {
...
}
要将流恢复到良好状态,您需要使用std::cin.clear()
,并且可能需要忽略不良字符,例如,使用std::cin.ignore()
。