getch() Question

Hello. I have tried to use the function getch(). I have a problen with it. getch(), I heard, will get the input without the user having to press ENTER with cin >>. But when I try using it in an instance like this -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    getch();
    if (getch() == 1)
    {
                cout << "You have chosen: 1" << endl;
    }
    else if (getch() == 2)
    {
                cout << "You have chosen: 2" << endl;
    }
    else if (getch() == 3)
    {
                cout << "You have chosen: 3" << endl;
    }
    else
    {
                cout << "You have chosen: NOTHING" << endl;
    }


I belive I may be using it incorrectly or something. There aren't any errors, but when I try to type in 1, 2, 3 or nothing, it won't get what I type. It only works when I press it about 3 times, but even if I do, it thinks I entered 0 even when I was entering 1.
Every time you call getch() you are having your program wait for input.
So line 1 waits for the user to type something and then throws away the keystroke the user entered. Line 2 waits a second time for a second keypress and checks it against ASCII character 1, which is non-printable. Since that check will likely be false, you'll hit line 6 where you'll wait a third time for a third keypress, etc.

1
2
3
4
5
6
char ch = getch();
if( ch == '1' ) {
   // etc
} else if( ch == '2' ) {
  // etc
}

Also, you'd be better off using std::cin.get() instead of getch() (if you mean the getch() from conio.h)
Thanks jsmith! That worked well!

@Poke386 - cin.get() doesn't work like I wanted it to. Thanks for the suggestion though.
Last edited on
Topic archived. No new replies allowed.