0

I need to make my while loop works until ESC button on keyboard is pressed.

char choose = NULL;
while( choose != 27)
{
    cout << "Choose (s), (e) or (n): ";
    cin.ignore();
    choose = cin.get();

    switch(choose){
    case 's': {SortRoutesByStartPoint(routeList, n); ShowRoutes(routeList, n, "Sorted list (s):"); break;}
    case 'e': {SortRoutesByEndPoint(routeList, n); ShowRoutes(routeList, n, "Sorted list (e):"); break;}
    case 'n': {SortRoutesByNumber(routeList, n); ShowRoutes(routeList, n, "Sorted list (n):"); break;}
    default: {cout << "Not found\n\n"; break;}
    }
}

But when I press ESC button it happends nothing. Why?
How to make it work?

PaperBirdMaster
  • 12,806
  • 9
  • 48
  • 94
Heidel
  • 3,174
  • 16
  • 52
  • 84
  • 1
    Possible duplicate of http://stackoverflow.com/questions/14214753/how-to-read-until-esc-button-is-pressed-from-cin-in-c? Check that one out. – pineconesundae Oct 16 '13 at 13:07
  • Yes, I have seen this question and I tried to use the first answer from it, but it doesn't work. – Heidel Oct 16 '13 at 13:10
  • Chances are ESC is being grabbed by your terminal so it never turns up in stdin. You'll probably have to set some terminal settings to get those keypresses - might be better to use some TUI library like CURSES to handle this stuff for you. – Magnus Oct 16 '13 at 13:20

2 Answers2

1

The simple answer is that you can't, at least not reliably, using the standard streams. If you're inputting from a terminal, you get what the OS gives you. And in general, it doesn't give you anything until enter has been pressed, and strips out a lot of characters for line editing and other things before that; there's a distinct change that ESC is among those characters.

When you want to read character by character (as you apparently do), you need some third party library, like curses. Or you'll have to write a lot of system dependent code yourself.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
0
#include <conio.h>

cout << "Choose (s), (e) or (n): ";
// cin.ignore();
// choose = cin.get();

choose =getche();
if(choice==0)  //an extended character code is next
  choice=getche();
Simple Fellow
  • 4,315
  • 2
  • 31
  • 44