i dont know how work getch in this code

i have a doubt with the funtion getch on this code
1
2
3
4
5
6
7
8
9
10
char a= NULL,b=NULL;
while(a!='a'){

if(kbhit()){
    a=getch();}

b=getch();
    cout << a;
    cout << b;
}


if i put the code like this, on the variable 'a' nothing save on it, only on 'b' unless i press the directiona arrow,that is the only thing that save on 'a'

but if i put this code without b=getch(), the variable 'a' save normaly any key

Really help on this please!!!


closed account (SECMoG1T)
Hello getch() doesn't return a char but an int value so using this condition on some compilers a!='a' would cause an infinite loop maybe you can use the c++ get() function instead

1
2
3
4
5
6
7
8
9
10
11
char a,b;
while(a!='a'){

if(kbhit()){
    std::cin.get(a);
}

 std::cin.get(b);
    cout << a;
    cout << b;
}
Last edited on
Here's what's happening:
- you start the program
- running at a billion+ instructions per second, the program almost instantly checks at line 4 to see if a key has been pressed. You're finger has moved 4 microns toward the 'a' key, but still no key is pressed.
- The program gets to line 7 and waits for input. At this point, it's actually going to wait until you press a letter and hit enter. Once you hit enter, the OS puts both characters in the cin stream. Line 7 reads the first one - the 'a' character.

If you want to look for keyboard input then you need to use the keyboard routines to get the key presses. Another example: if you press the shift key, then kbhit() returns true, but cin will contain no input.
Topic archived. No new replies allowed.