0

I've written a C program to count the number of occurrences of an entered character. When I execute,I could only enter the file name.Before I enter the character to be counted , the next statement executes.The output I get is shown below.

Enter the file name
test.txt
Enter the character to be counted 
File test.txt has 0 instances of

Here is my code

#include<stdio.h>
#include<stdlib.h>
int main()
{
  FILE *fp1;
  int cnt=0;
  char a,ch,name[20];
  printf("Enter the file name\n");
  scanf("%s",name);
  //fp1=fopen(name,"r");
  printf("Enter the character to be 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 to resolve this?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
gayathri
  • 3
  • 1

1 Answers1

5

It's a common beginners problem, especially when using the scanf family of functions.

The problem is that when you enter the file-name, and press Enter, the scanf function reads the text but leaves the Enter key, the newline, in the input buffer, so when you next read a character it will read that newline.

The solution is very simple: Tell scanf to read and discard any leading white-space by putting a single space in the scanf format:

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

If you follow the link to the scanf reference it will tell you that almost all formats automatically reads and discards leading white-space, one of the three exceptions is just the format to read single characters, "%c".

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621