Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

getch() from curses.h is:

get[ting]... characters from curses terminal keyboard

getchar() from stdio.h is:

read[ing] the next character from [stdin] and return[ing] it as an unsigned char cast to an int, or EOF on end of file or error.

So, your first example is reading the newline character ('\n') left on stdin from the scanf() call, everything works.

Your second example, you're not using or linking to curses and so in no-delay mode, if no input is waiting, the value ERR is returned from getch(). ERR is -1, '\n' is 10. They don't match so you go into an infinite loop waiting for -1==10

int getchar(void) vs. int getch(void);

Both return an int.

Both may return values outside an 8-bit range, thus when saving the result, it should be saved in an int.

--

Difference between the 2:

getchar() is in the C spec. getch(); is not.

The return value from getchar() will display on the screen. From getch() will not.

getchar() will go into an infinite while() loop should the EOF condition occur. Better to use:

int c; 
while((c = getchar()) !='\n' && c != EOF);

getch() returns ERR on error or timeout. There is some variation of the functionality on various systems - it is not specified in C. Some allow an option to return immediately if there is no key in the queue.

When pressing Enter, getchar() returns '\n'.
getch() returns the keycode. which may match '\n', '\r' or others.
This is OP's immediate problem. @Ingo Leonhardt

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top