Why does the switch always work by default? (with break enabled;)

C ++ newbie is trying to create a simple text game on a 2D array.

When I use the switch as shown. It will always print the default value, no matter what else happens.

From other threads and forums, I found that it probably has something to getch() with getch() and that it returns char , as well as \n .

I tried for an hour, but I can’t solve it. The reason I use getch() is this: C ++ changing the canonical mode in windows (for reference).

Part of my code:

 //Set up game field generateField(); setPlayerStart(); //printGameInfo(); TO BE MADE //Start game while loop int userInput; do{ //system("cls"); DISABLED FOR TESTING PURPOSES printField(); userInput = getch(); switch(userInput){ case 72:{ //ARROW UP cout << "1What" << endl; //ALSO FOR TESTING PURPOSES break; } case 80:{ //ARROW DOWN cout << "2What" << endl; break; } case 75:{ //ARROW LEFT cout << "3What" << endl; break; } case 77:{ //ARROW RIGHT cout << "4What" << endl; break; } case 113:{ //"q" return false; //Quit game } default:{ cout << "Default..." << endl; } } } while(userInput != 5); 
-2
c ++ windows switch-statement
source share
2 answers

Since this is Windows, you can use ReadConsoleInput to read key events. I divided the parts into functions, but I really don't think the handleInput return semantics are all that great.

 #include <iostream> #include <stdexcept> #include <windows.h> HANDLE getStdinHandle() { HANDLE hIn; if ((hIn = GetStdHandle(STD_INPUT_HANDLE)) == INVALID_HANDLE_VALUE) { throw std::runtime_error("Failed to get standard input handle."); } return hIn; } WORD readVkCode(HANDLE hIn) { INPUT_RECORD rec; DWORD numRead; while (ReadConsoleInput(hIn, &rec, 1, &numRead) && numRead == 1) { if (rec.EventType == KEY_EVENT && rec.Event.KeyEvent.bKeyDown) { return rec.Event.KeyEvent.wVirtualKeyCode; } } throw std::runtime_error("Failed to read input."); } bool handleInput(WORD vk) { switch (vk) { case VK_UP: std::cout << "up\n"; break; case VK_DOWN: std::cout << "down\n"; break; case VK_LEFT: std::cout << "left\n"; break; case VK_RIGHT: std::cout << "right\n"; break; case 'Q': //it Windows; ASCII is safe return true; } return false; } int main() { try { auto hIn = getStdinHandle(); while (auto vk = readVkCode(hIn)) { if (handleInput(vk)) { return 0; } } } catch (const std::exception &ex) { std::cerr << ex.what(); return 1; } } 

Other useful links:

+4
source share

Um, I suppose you forgot how to get extended keys.

It comes with 0xe0 when using the extended keys, and it comes with 0x00 when the function key (F1-F12)

Change it

 userInput = getch(); 

in

 userInput = getch(); if (userInput == 0xe0) // for extended keys { userInput = getch(); } else if (userInput == 0x00) // for function keys { userInput = getch(); } 
+4
source share

All Articles