Till Crueger <Ti****@gmx.net> wrote:
Hi,
I have a little problem with the following code:
#include <stdio.h>
int main(void) {
char input='\0';
while(input!='q') {
printf("Menu\n");
fflush(stdout);
scanf("%c",&input);
Try:
scanf(" %c", &input);
(leading space will eat whitespace in the input) /* do something */
}
}
After I get an input there is still a trailing newline. However I always
thought the next scanf would consume this newline.
scanf is a very determinate function, it won't do anything unless
you tell it to.
I checked with the FAQ,
but all I found was section 12.18 which covers this issue a bit. The
solution it gives is to only use scanf(), which in this case I do. Any
other hints on what to do about this?
scanf is perhaps not good for every task, especially not for user input
(scanf is for _formatted_ input; user must be very orderly to feed it
with the right data). To see this try:
Menu
abcd<Enter>
Menu
Menu
Menu
Menu
I think in general fgets() is better. But for simple cases like above
(where the code is not a "production" code), scanf() is all right
too, and maybe easier to use (if you know what you're doing).
As a learning exercise, try:
scanf("%c ", &input); //space is after conversion specifier
printf("entered: %c\n", (int)input);
and explain the funny effect. Good luck!
--
Stan Tobias
mailx `echo
si***@FamOuS.BedBuG.pAlS.INVALID | sed s/[[:upper:]]//g`