scanf没有按预期工作

时间:2015-12-25 03:45:58

标签: c scanf

我尝试在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之后执行而没有第二次输入。

4 个答案:

答案 0 :(得分:1)

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

所以改变这个

scanf("%c",&val);

进入这个

scanf(" %c",&val);

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

在格式化部分中放置一个空格会使剩余的换行符消失。

答案 1 :(得分:0)

您可以使用div#something:hover .hide{ pointer-events: none; color: GrayText; background-color: #ddd; background: #ddd; }

fgets()

或清除#include<stdio.h> 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

另请参阅C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf

答案 2 :(得分:0)

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

我不知道为什么,但代码高于工作......

scanf("%d",&val);

答案 3 :(得分:0)

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

相关问题