samedi 25 avril 2015

counting the number of times a character appears in a file in a case insensitive manner using C language


The problem statement : a C program to count the number of times a character appears in the File. character is considered Case insensitive. I have converted both the input character and character from the file to upper case so that none of the occurrence of the character goes uncounted. but when am executing this on an online editor am getting the result as "wrong answer" the editor isn`t accepting this code. what is the mistake in this code??

    #include<stdio.h>
    #include<ctype.h>
    #include<stdlib.h>
    int main
    {
     FILE *fp;
     char filename[20];
     char character;
     char compare;
     int to_upper1;
     int to_upper2;
     int count=0;
     printf("\nEnter the file name");
     scanf("%s", filename);
     fp = fopen(filename,"r");
     if(fp == NULL)
     {
       exit(-1);
     }
     printf("\nEnter the character to be counted");
     scanf("%c", &character);
     to_upper1 = toupper(character);
     while((compare = fgets(fp)) != EOF)
     {
       to_upper2 = toupper(compare);
       if(to_upper1 == to_upper2)
          count++;
     }
     printf("\nFile \'%s\' has %d instances of letter \'%c\'", filename, count,      character);
return 0;
}


Aucun commentaire:

Enregistrer un commentaire