1

Trying to figure out why this would be an endless loop when you select y. Shouldn't it leave the do while loop when the user selects y or Y?

#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;
}
itsAr_no
  • 11
  • 1
  • if you want quick fix, change the `while (choice != 'y'|| choice != 'Y')` to `while (cin)` – SHR Nov 27 '16 at 00:20
  • 4
    Hmm `(choice != 'y'|| choice != 'Y')` isn't that always true? I mean even if choice == 'y' its the not 'Y' if it is 'Y' its not 'y' if it is any other letter its also true.. – drescherjm Nov 27 '16 at 00:23
  • I was following what the book was asking. "Write a do-while loop that displays whether a user entered an int even or odd. The code should then ask the user if he or she wants to test another number. The loop should repeat so long as the user enters Y or y. Use a logical OR operator in the do-while loop test." – itsAr_no Nov 27 '16 at 00:36
  • Actually @drescherjm is right. The actual condition will always render true, because when choice == y, then choice != Y, and false || true = true. The correct condition should be !( choice == 'y' || choice == 'Y'), which is equivalent to (choice != 'y' && choice != 'Y'). – Alberto Hormazabal Nov 27 '16 at 00:53

1 Answers1

5

choice is an int; you can't read the letter y into it. When you try, it "breaks" cin, causing your endless loop.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101