c - Character is not accepted -


this question has answer here:

i've written c program count number of occurrences of entered character. when execute,i enter file name.before enter character counted , next statement executes.the output shown below.

 enter file name test.txt enter character counted  file test.txt has 0 instances of 

here code

#include<stdio.h> #include<stdlib.h> int main() {   file *fp1;   int cnt=0;   char a,ch,name[20];   printf("enter file name\n");   scanf("%s",name);   //fp1=fopen(name,"r");   printf("enter character counted\n");   scanf("%c",&ch);   fp1=fopen(name,"r");   while(1)   {     a=fgetc(fp1);     if (a==ch)       cnt=cnt+1;     if(a==eof)           break;   }   fclose(fp1);   printf("file %s has %d instances of %c",name,cnt,ch);   return 0; } 

how resolve this?

it's common beginners problem, when using scanf family of functions.

the problem when enter file-name, , press enter, scanf function reads text leaves enter key, newline, in input buffer, when next read character read newline.

the solution simple: tell scanf read , discard leading white-space putting single space in scanf format:

scanf(" %c",&ch); //     ^ //     | // note leading space 

if follow link scanf reference tell formats automatically reads , discards leading white-space, 1 of 3 exceptions format read single characters, "%c".


Comments