我尝试在Ubuntu 15.10中执行以下简单代码,但代码的行为与预期不同。
#include<stdio.h>
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("%c",&val);
-->scanf(" %c",&val);
i<20
-->i<20 && a[i]
scanf("%s",a);
-->scanf("%19s", a);
(i<20
-->ia[i]
)ia[i]
我的打字错误为a[i]
。 - BLUEPIXYscanf
的返回值?同时确保它不会越界数组。 - Ed Heal