The while loop in C++ skips the user input line

47 Views Asked by At

If you enter a character as the input for the first question the switch statement should throw you into the default clause, and it does. But after that, the following while loop just keeps running without waiting for user input. Why is this?

#include <iostream>

using namespace std;

int main()
{
    cout << "Difficulty Levels\n\n";
    cout << "1 - Easy\n";
    cout << "2 - Normal\n";
    cout << "3 - Hard\n\n";

    int choice;
    cout << "Choice: ";
    cin >> choice;

    switch (choice)
    {
    case 1:
        cout << "You picked Easy.\n";
        break; // if no break, the code will evaluate choice in following cases
    case 2:
        cout << "You picked Normal.\n";
        break;
    case 3:
        cout << "You picked Hard.\n";
        break;
    default: // execute this if choice doesn't match any condition
        cout << "You made an illegal choice.\n";
    }
    
    char again = 'y'; // setting to "y" does not work !
    while (again == 'y')
    {
        cout << "\n**Played an exciting game**";
        cout << "\nDo you want to play again? (y/n): ";
        cin >> again;
    }
    cout << "\nOkay, bye.";

    return 0;
}
0

There are 0 best solutions below