如何解决我的 while 循环中的 cin.fail 是否导致我的输出无限循环?
我有一个 while true 循环来强制用户输入正确类型的输入并确保输入在 1-8 之间。当我尝试使用 !cin 或 cin.fail 检查输入是否为整数时,我的输出会永远循环下去。
// Taking amount of courses user is enrolled in
int courses = 0;
while (true)
{
cout << "How many courses do you want to take?\n If this is not the first time you are seeing this prompt,\n that means you entered a faulty input. Enter a number \n between 1 and 8.";
cin >> courses;
if (cin.fail())
{
cout << "You entered a non integer value such as Z or 0.2\n. Please enter an integer value\n";
}
if (courses > 0 && courses<= 8)
{
cout << "You have entered " << courses << " courses\n";
break;
}
}
while true 循环是否会导致问题,如果是,我该如何修复它,同时具有相同的运行效果,直到用户输入 1-8 之间的数字。
输出的样子:
If this is not the first time you are seeing this prompt,that means you entered a faulty input. Enter a number
between 1 and 8.You entered a non integer value such as Z or 0.2
. Please enter an integer value
How many courses do you want to take?
If this is not the first time you are seeing this prompt,that means you entered a faulty input. Enter a number
between 1 and 8.You entered a non integer value such as Z or 0.2
我不得不使用 ide 控制台中的停止按钮强制停止它。
编辑:如果 cin.fail 不正确,我的程序就可以工作。如果用户从头开始输入整数,则输出不会循环。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。