无法使用scanf两次扫描字符串然后扫描字符

时间:2014-11-15 11:03:18

标签: c stdin scanf

我尝试使用scanf两次扫描字符串,然后扫描字符。它首先扫描字符串,不执行第二个scanf。当我在单个%s中同时使用%cscanf时,它可以完美运行。你能告诉我为什么会这样吗?

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

1 个答案:

答案 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;
}
相关问题