This question already has answers here:
Why do I get an infinite loop if I enter a letter rather than a number? [duplicate]

(4个答案)


4年前关闭。




试图弄清楚为什么选择y时这将是一个无限循环。用户选择y或Y时,是否不应该离开do while循环?
#include <iostream>
using namespace std;

int main()
{
    int choice;


    do {
        cout << "Enter a number. If you would like to quit, press y.";
        cin >> choice;

        if (choice % 2 == 1)
        {
            cout << "Odd \n";
        }
        else
        {
            cout << "Even \n";
        }

    } while (choice != 'y'|| choice != 'Y');


    return 0;
}

最佳答案

choiceint;您无法将字母y读入其中。尝试时,它会“破坏” cin,从而导致无限循环。

关于c++ - 做循环无尽,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40824486/

10-13 08:33