Why does following program produce two output message at the same time, without asking开发者_开发技巧 for any input from the user???
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char input;
do {
printf("Enter a single character: \n");
scanf("%c", &input);
printf("The ordinal value is %d. \n",input);
} while(input != '#');
return 0;
}
The output is followings:
Enter a single character:
s
The ordinal value is 115.
Enter a single character:
The ordinal value is 10.
Enter a single character:
Terminal input is read line at a time unless you specify otherwise; scanf
reads one character as specified, leaving the newline you typed afterward to send the line in the input buffer for the next pass of the loop. Consider reading input by lines and using sscanf()
or similar to parse those lines.
Just insert getchar(); after your call to scanf. This will eat the newline. The suggestion to use scanf("%c\n", &input); seems sound, but I've never found it to work well; I wonder if anyone can tell me why?
精彩评论