Click here to Skip to main content
15,908,673 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This program is supposed to show the number of repetition of each alphabet in a given text file. But it displays a list mostly of zeros.
#include <stdio.h>
#include <stdlib.h>
#include "Ctype.h"
#define ABC 26
int main(int argc,char *argv[])
    FILE *fp;
    int i;
    char alfa[ABC],ch;
        printf("The file %s cannot be opened",argv[1]);

    while((ch=fgetc(fp))!=EOF) if(toupper(ch)>=65&&toupper(ch)<=91) ++alfa[toupper(ch)-'A'];

        for(i=0;i<ABC;i++) printf("%c is repeated %d times\n",'a'+i,alfa[i]);


What I have tried:

I added a condition before the counting loop to see if it might resolve the issue. I also experienced different text files but it always gives the same wrong results.
Updated 28-Feb-23 11:20am


Should be instead
if ( (fp=fopen(argv[1],"r")) == NULL )

As you could have easily recognized if you had properly indented your code.
Share this answer
An assignment has a lower priority in C than a comparison.
if(fp = fopen(argv[1], "r") == NULL)

The compiler could also report this because it has problems with the assignment:
error C2440: "=": "bool" cannot be converted to "FILE *".

At this point, it would otherwise have been noticed.
while ((ch = fgetc(fp)) != EOF)

I would like to note that includes from supplied headers should be written with angle brackets.
// #include "Ctype.h"
#include <ctype.h>
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900