Search code examples
c++switch-statementgetch

Whenever i run the code my default case always runs with the other cases (C++)


I have used the Break too at the end of every case but it's not breaking it. I think _getch() is taking two inputs at a time or it always has some garbage data at the start of each loop.

Here's the code generating this issue.

#include <conio.h>
#include <iostream>
using namespace std;

int main()
{
    int c = 0;
    while (1)
    {
        c = 0;

        switch ((c = _getch())) {
        case 72:
            cout << endl << "Up" << endl;//key up
            break;
        case 80:
            cout << endl << "Down" << endl;   // key down
            break;
        case 75:
            cout << endl << "Left" << endl;  // key left
            break;
        case 77:
            cout << endl << "Right" << endl;  // key right
            break;
        default:
            cout << endl << "null" << endl;  // not arrow
            break;
        }

    }

    return 0;
}

[Here my output]


Solution

  • For the arrow keys two values are generated. The first one is 0xE0 to indicate that the following one is something out of the ordinary.

    Your code fixed:

    #include <conio.h>
    #include <iostream>
    
    int main()
    {
        int c = 0;
        do {
            c = _getch();
            if (c == 0xE0)
                c = _getch();
    
            switch (c) {
            case 72:
                std::cout << "Up\n";
                break;
            case 80:
                std::cout << "Down\n";
                break;
            case 75:
                std::cout << "Left\n";
                break;
            case 77:
                std::cout << "Right\n";
                break;
            default:
                std::cout << "null\n";
                break;
            }
    
        } while (c != 0x1B /* esc */);
    }