我的 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 (将#修改为@)