我尝试使用scanf
两次扫描字符串,然后扫描字符。它首先扫描字符串,不执行第二个scanf
。当我在单个%s
中同时使用%c
和scanf
时,它可以完美运行。你能告诉我为什么会这样吗?
#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;
}
另一个有效的程序
#include<stdio.h>
int main()
{
char s[100],ch;
scanf("%s %c",s,&ch); //this works!
printf("%s %c",s,ch);
return 0;
}
答案 0 :(得分:3)
请在%c
中的scanf()
之前添加空格。
读取字符串后会出现换行符,因此%c
#include<stdio.h>
int main()
{
char s[100],ch;
scanf("%s",s);
scanf(" %c",&ch);
printf("%s %c",s,ch);
return 0;
}