-
printf and scanf command
I was wondering if anyone could tell me why the second scanf is skipped after i enter one number and then hit enter? I am trying read two values from the keyboard and send them through a pipeline. Does anyone know which function to call for the program to store the keyboard character that is pressed to a char variable right after the key has been pressed without a following enter (line carriage)? Thanks!
Code:
while(1)
{
printf("Please select the elevator car letter (A, B, C) or Up/Down arrows : ");
scanf("%c", &temp);
printf("%c\n", temp);
// Add character append function calls
printf("Please enter the floor number (0 - 9) : ");
scanf("%c", &temp);
printf("%c\n", temp);
// Add character append function calls
}
-
It's because scanf()'s %c matches newlines as well as ordinary characters. When you tell scanf to read a number and enter "123\n", it takes the "123" and leaves the "\n" for the next scanf to read when looking for a character.
There are lots of ways around this problem. The best is probably to read input as lines with fgets() and then use sscanf() to parse those lines.
Code:
char buffer[BUFSIZ];
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%c", &c);
/* or, with error checking: */
if(!fgets(buffer, sizeof(buffer), stdin);
|| sscanf(buffer, "%c", &c) != 1) {
perror("Error reading stdin");
}
Another way is to simply discard any trailing whitespace between scanf()s. You can do this with a single
or better yet, in case there are multiple newlines or spaces:
Code:
while(getchar() != '\n');
BTW -- this is the C++ forum, and cin and cout should be used in C++ instead of scanf() and printf().
-
Note that this is C, not C++. And of course, the second scanf isn't skipped -- there's a perfectly good character waiting to be input, namely the enter key from the first time. You can do another scanf, if you like, or to actually do it in a reasonable way, do scanf("%d"), since scanf skips whitespace when looking for numbers. (Of course, temp would then need to be an int and not a char.)