unable to use scanf twice for scanning a string an

2019-08-13 19:03发布

问题:

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;
}


标签: c stdin scanf