Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference in the usage of getch() and getchar() for clearing input buffer?

CODE 1:-

char ch1, ch2;

printf("Input the first character:");

scanf("%c", &ch1); 

while(getchar()!='\n');

printf("Input the second character:");

ch2 = getchar();

In this case while(getchar()!='\n');, clears the effect of enter-key pressed for first input.

CODE 2:-

char ch1, ch2;

printf("Input the first character:");

scanf("%c", &ch1); 

while(getch()!='\n');

printf("Input the second character:");

ch2 = getchar();

In this case while(getch()!='\n');, do not clears the effect of enter-key pressed for first input. AND THE LOOP TURNS OUT TO BE INFINITE.

What is the difference in the functioning of getch() and getchar() this case?

like image 583
kevin gomes Avatar asked Feb 02 '26 15:02

kevin gomes


1 Answers

From man getch:

Note that some keys may be the same as commonly used control keys, e.g., KEY_ENTER versus control/M, KEY_BACKSPACE versus control/H. Some curses implementations may differ according to whether they treat these control keys specially (and ignore the terminfo), or use the terminfo definitions. Ncurses uses the terminfo definition. If it says that KEY_ENTER is control/M, getch will return KEY_ENTER when you press con- trol/M.

That means getch() returns KEY_ENTER instead of '\n' when it reads the enter key, and thus your while loop never terminates.

like image 50
Ingo Leonhardt Avatar answered Feb 05 '26 07:02

Ingo Leonhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!