vendredi 8 février 2019

Switch statement jumps to default case from another case std::cin buffer

Problem Summary :

I have a switch case statement where I enter a case (say 'case i') in this question based on user input. Later inside this case, I grab another user input (std::cin >>) and test whether it is integer using std::cin.fail(). If it was not an integer, then I reset std::cin using std::cin.ignore() and std::cin.clear() and then do some std::cout operation and break. But it so happens that the std::cin buffer from this recent input gets carried on in the program (even after giving a break statement) and the program executes the default statement. Why does this happen ?

This is my code :

int main() {
std::cout << "Welcome to the deck of cards game !\n\n";

while (1) {
    std::cout << "\na.) To shuffle the cards, press 'S';\n" <<
              "b.) To view the deck on screen, press 'D';\n" <<
              "c.) To view a specific card from index, press 'I;\n" <<
              "d.) To quit program, press 'Q'\n" << std::endl;

    char input = 'P';

    std::cin >> input;

    if (input == 'q' || input == 'Q') break;
    else {
        switch (input) {

        case 'S': case 's': {
            std::cout << "Pack was shuffled" << std:endl;
            break;
        }

        case 'D': case 'd': {
            std::cout << "Imagine you are viewing the deck" << std::endl;
            break;
        }

        case 'I': case 'i': {
            std::cout << "Please enter index number of card" << std::endl;
            int index = 0;
            std::cin >> index;
            if (std::cin.fail()) {
                std::cin.ignore(std::numeric_limits<std::int32_t>::max());
                std::cin.clear();
                std::cout << "Error : Input was not an integer" << std::endl;
                break;
            } else {
                std::cout << "Imagine you are now seeing a specific card" << std::endl;
                break;
            }
            break;
        }

        default: {
            std::cout << "The character " << input <<
                      " is not an acceptable character.\n" << std::endl;
            break;
        }
        }
    }
  }
}

I expect the output to be like this :

a.) To shuffle the cards, press 'S';
b.) To view the deck on screen, press 'D';
c.) To view a specific card from index, press 'I;
d.) To quit program, press 'Q'

i
Please enter index number of card
y
Error : Input was not an integer

But the actual output is like this :

a.) To shuffle the cards, press 'S';
b.) To view the deck on screen, press 'D';
c.) To view a specific card from index, press 'I;
d.) To quit program, press 'Q'

i
Please enter index number of card
y
Error : Input was not an integer
The character y is not an acceptable character.

Aucun commentaire:

Enregistrer un commentaire