我正在尝试将一个简单的问题和数字检查器编码到我的第一个 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;
}
}