问题
I tried using scanf
twice for scanning a string and then scanning a char. It scans string first and does not execute the second scanf
. When I use both %s
and %c
in a single scanf
it works perfectly. Can you tell me why this happens?
#include<stdio.h>
int main()
{
char s[100],ch;
scanf("%s",s);
scanf("%c",&ch); //this does not work
printf("%s %c",s,ch);
return 0;
}
another program which works
#include<stdio.h>
int main()
{
char s[100],ch;
scanf("%s %c",s,&ch); //this works!
printf("%s %c",s,ch);
return 0;
}
回答1:
Please add a space before %c
in scanf()
.
There is a newline character after the string is read so this is being taken by %c
#include<stdio.h>
int main()
{
char s[100],ch;
scanf("%s",s);
scanf(" %c",&ch);
printf("%s %c",s,ch);
return 0;
}
来源:https://stackoverflow.com/questions/26945123/unable-to-use-scanf-twice-for-scanning-a-string-and-then-scanning-a-char