Log*_*aso 6 c++ cin infinite-loop while-loop
我正在尝试将一个简单的问题和数字检查器编码到我的第一个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;
}
Run Code Online (Sandbox Code Playgroud)
以下是我当前的代码以及您的建议:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
#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;
}
Run Code Online (Sandbox Code Playgroud)
好的.std::cin.clear();负责重置失败位.std::cin.ignore删除流中剩余的任何错误输入.而且我已经调整了停止条件.(这isDigit是一个冗余的检查,如果生命在1到3之间,那么显然它是一个数字).
| 归档时间: |
|
| 查看次数: |
10956 次 |
| 最近记录: |