Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

c - scanf not working as expected

I tried to execute the following simple code in ubuntu 15.10 But the code behaves odd than expected

#include<stdio.h>
int main(){
int n,i=0;
char val;
char a[20];

printf("
Enter the value : ");
scanf("%s",a);
printf("
Enter the value to be searched : ");
scanf("%c",&val);

int count=0;
for(i=0;i<20;i++){
 if(a[i]==val){
   printf("
%c found at location %d",val,i);
   count++;
 }
}
printf("
Total 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

The second scanf to get the value to be searched seems not to be working. The rest of the code executes after the first scanf without getting input second time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After first scanf(), in every scanf(), in formatting part, put a whitespace

So change this

scanf("%c",&val);

into this

scanf(" %c",&val);

Reason is, scanf() returns when it sees a newline, and when first scanf() runs, you type input and hit enter. scanf() consumes your input but not remaining newline, so, following scanf() consumes this remaining newline.

Putting a whitespace in formatting part makes that remaining newline consumed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...