scanf没有按预期工作

我尝试在ubuntu 15.10中执行以下简单代码但是代码的行为比预期的要奇怪

#include int main(){ int n,i=0; char val; char a[20]; printf("\nEnter the value : "); scanf("%s",a); printf("\nEnter the value to be searched : "); scanf("%c",&val); int count=0; for(i=0;i<20;i++){ if(a[i]==val){ printf("\n%c found at location %d",val,i); count++; } } printf("\nTotal occurance of %c is %d",val,count); return 0; } output: -------------------------- Enter the value : 12345678 Enter the value to be searched : Total occurance of is 0 

获取要搜索的值的第二个scanf似乎不起作用。 其余代码在第一次scanf之后执行,而不是第二次输入。

在第一次scanf()之后,在每个scanf()中,在格式化部分中,放一个空格

所以改变这个

 scanf("%c",&val); 

进入这个

 scanf(" %c",&val); 

原因是,scanf()在看到换行符时返回,当第一次scanf()运行时,键入input并按Enter键。 scanf()会消耗您的输入但不会保留换行符,因此,在scanf()之后会消耗此剩余的换行符。

在格式化部分中放置空格会使剩余的换行消耗掉。

你可以使用fgets()

 #include int main() { int n, i = 0; char val; char a[20]; printf("\nEnter the value : "); fgets(a, 20, stdin); printf("\nEnter the value to be searched : "); scanf("%c", &val); int count = 0; for (i = 0; i < 20; i++) { if (a[i] == val) { printf("\n%c found at location %d", val, i); count++; } } printf("\nTotal occurance of %c is %d", val, count); return 0; } 

或清除stdin

 #include void clearstdin(void) { int c; while ((c = fgetc(stdin)) != EOF && c != '\n'); } int main() { int n, i = 0; char val; char a[20]; printf("\nEnter the value : "); scanf("%s",a); clearstdin(); printf("\nEnter the value to be searched : "); scanf("%c", &val); int count = 0; for (i = 0; i < 20; i++) { if (a[i] == val) { printf("\n%c found at location %d", val, i); count++; } } printf("\nTotal occurance of %c is %d", val, count); return 0; } 

另外,请参阅C:多个scanf,当我输入一个scanf的值时,它会跳过第二个scanf

 printf("\nEnter the value : "); scanf("%s",a); printf("\nEnter the value to be searched : "); scanf("%d",&val); // here is different 

我不知道为什么,但上面的代码……

 scanf("%d",&val); 

您可以使用“%c”代替“%c”作为格式字符串。 空白导致scanf()在读取字符之前跳过空格(包括换行符)。