问题
I'm not new at writing code. But I'm just learning C language. I cannot understand this subject. Perhaps it is not an issue but now it is an issue for me. Would you please explain that?
Here is code, where I encounter with this:
#include <stdio.h>
int main(int argc, char *argv[])
{
char letter;
while (1)
{
printf("Enter a letter:\n");
scanf("%c", &letter);
switch (letter)
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'u':
case 'U':
case 'o':
case 'O':
printf("%c is a vowel letter.\n", letter);
break;
case 'y':
case 'Y':
printf("%c is sometimes a vowel letter.\n", letter);
break;
default:
printf("%c is not a vowel letter.\n", letter);
}
}
return 0;
}
Output:
Enter a letter: a a is a vowel letter. Enter a letter: is not a vowel letter. Enter a letter:
回答1:
Change the format from "%c"
to " %c"
to make scanf discard all whitespace (as determined by isspace(), " \v\f\r\n\t"
in the POSIX and C locales) before assigning the next character, whatever it may be.
Maybe a better alternative, read a whole line with fgets and then use sscanf
to parse it instead.
As an aside, take care that scanf
can always fail. On success, it returns the number of assigned arguments.
Also, I strongly suggest you read the scanf
-manpage I linked above (or even better, the C standard on scanf
), because there are quite a lot of pitfalls you may not know yet.
来源:https://stackoverflow.com/questions/26691924/why-does-scanf-function-get-automatically-previous-n-value-and-how-can-i-esca