Problems with the switch

1

I'm experiencing problems with this code, when running it the default runs also being that at no time did I enter any data other than what is 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

Can anyone tell me what's happening, does it have to be with the buffer of the keyboard that gets the \n when I enter the data? How do I resolve this?

    
asked by anonymous 15.10.2016 / 21:24

2 answers

1

Each time you add a note, you are adding x\n to buffer , so checking while re-runs to \n . I recommend you create a special case for \n to not run the default . Or I recommend you even replace (grade = cin.get()) != EOF because otherwise the buffer will always be written to the variable grade .

    
15.10.2016 / 22:18
0
  

... Is there a buffer with the keyboard that catches the \n when I enter the data? How do I resolve this?

The cin.get should probably be returning in addition to the typed character, the new line also . One way to work around this is to use 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 )
    {
        // ...
    }
}
    
15.10.2016 / 22:41