Problems with the switch

Asked

Viewed 63 times

1

I am facing problems with this code, when running it the default runs also and in no time I entered with some data other than in the cases.

// faz loop até usuário digitar a sequência de teclas de fim do arquivo
while ((grade = cin.get()) != EOF)
{
    // determina a nota que foi inserida
    switch (grade)
    {
        case 'A':
        case 'a':
           aCount++;
           break;

        case 'B':
        case 'b':
           bCount++;
           break;

        case 'C':
        case 'c':
           cCount++;
           break;

        case 'D':
        case 'd':
           dCount++;
           break;

        case 'F':
        case 'f':
           fCount++;
           break;

        default:
           cout << "Incorrect letter grade entered." << " Enter a new grade." << endl;
    } // fim do switch
} // fim do while

Could someone tell me what’s going on, has to do with the buffer of the keyboard that picks up the \n when do I enter the data? How to resolve this?

  • Managed to solve the problem? has something to improve on some of the answers?

2 answers

1

Every time you add a note, you’re adding x\n at the buffer, then the verification of the while runs again to \n. I recommend you create a special case for \n not to be executed the default. Or recommend even more you replace the (grade = cin.get()) != EOF why if not the buffer all will always be saved in variable grade.

0

...has to do with the keyboard buffer that picks up the \n when do I enter the data? How to resolve this?

Probably the cin.get must be returning beyond the typed character, the new line too. One way to solve this is to use the cin.ignore to ignore the new line:

#include <limits>
....

char grade;

while ((grade = cin.get()) != EOF)
{
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Ou cin.ignore()
    switch ( grade )
    {
        case 'A':
        case 'a':
           cout << "A" << endl;
           break;
        // ...
    }
}

See DEMO

Another alternative is:

while (cin >> grade)
{
    switch ( grade )
    {
        // ...
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.