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?
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.