Rebecca
Rebecca

Reputation: 25

Counting the number of occurrence of a character in a file in case-sensitive way

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
    FILE *fp1;
    char ch,f[100],c,d;
    int ct=0;

    printf("Enter the file name\n");
    scanf("%s",f);   

    fp1=fopen(f,"r");

    printf("Enter character:");
    scanf(" %c",&c);

    c=toupper(c);

    do 
    { 
       ch=fgetc(fp1);
       d=toupper(ch);
       if(c==d||c==ch)
          ++ct;

    } while(ch!=EOF);

    fclose(fp1);

    printf("\n");
    printf("%d",ct);

    return 0;

}

here my file contains aAaAaA and when I execute this code, I am getting 6 characters in the file but I should get it as 3 characters because a and A are case insensitive. What's wrong with this code?

Upvotes: 0

Views: 3877

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

In your code, essentially, you're incrementing the counter unconditionally.

if(c==d   ||   c==ch)
      ^            ^
      |            |
UPPERCASE       original

will increment the counter for both the cases.

As the code is currently written . for an input of a or A, c is always A, so

  • When a is read from file, d is A, so, c==d gives TRUE, increments the counter
  • When A is read from file, ch is A, so as d thereby c==d gives TRUE, increments the counter.

What you actually want is to consider the input as case-sensitive [A and a should be counted as differnt characters.]

Also, as Mr. @coolguy mentioned in his comments, check the return value of fopen() for success before using the returned pointer.

Solution:

  1. Do not convert the input using toupper(). Use the actual input instead.
  2. If you want case-sensible operation, only check for the input by user and input from file, without any case-conversion. A pseudocode may look like

.

 #include<stdio.h>
 #include<stdlib.h>
 #include<ctype.h>

int main(void)
{
    FILE *fp1 = NULL;
    char ch,f[100],c,d;
    int ct=0;

    printf("Enter the file name\n");
    scanf("%s",f);   

    fp1=fopen(f,"r");

    if (!fp)
    {
        printf("Cannot open file for reading\n");
        exit(-1);
    }

    printf("Enter character:");
    scanf(" %c",&c);

    do 
    { 

        ch=fgetc(fp1);

        if(ch == c)
            ++ct;

    }while(ch!=EOF);

    fclose(fp1);    
    printf("%d\n",ct);    
    return 0;    
}

Upvotes: 3

Related Questions