meksun
meksun

Reputation: 41

Printing number of letter occurrences in a string

void
countChar()
{
    FILE *fp = fopen("source.txt", "r");

    char string[100], i;
    int c = 0, count[26] = {0}, x, y;

    for (i = 0; !feof(fp); i++) {
            fgets(string, 30, fp);
    }

    while (string[c] != '\0') {
        if (string[c] >= 'a' && string[c] <= 'z') {
            x = string[c] - 'a';
            count[x]++;
        }
        if (string[c] >= 'A' && string[c] <= 'Z') {
            y = string[c] - 'A';
            count[x]++;
        }       

        c++;
    }

    for (c = 0; c < 26; c++)
        if (count[c] != 0)
            printf("%c = %d\n", c + 'A', count[c]);
}

I have this code wherein I'm supposed to be counting the number of occurrences of a letter in a string, but I can't seem to print out the number of capital letters correctly.

small letters This is how it is when I type in small letters.

capital letters And this is how it is when I type in capital letters.

Upvotes: 0

Views: 71

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311146

For starters this loop

for (i = 0; !feof(fp); i++) {
        fgets(string, 30, fp);
}

does not make sense. It is unclear why there is used the magic number 30. And after the loop the array string will contain the last record read from the file.

The loop should look like

while ( fgets( string, sizeof( string ), fp ) != NULL )
{
    // count within the loop letters.
}

And within the body of the loop all characters should be countered.

Moreover in this if statement

    if (string[c] >= 'A' && string[c] <= 'Z') {
        y = string[c] - 'A';
        count[x]++;
    }  

there is a typo. There should be at least

count[y]++;

instead of

count[x]++;

It is a bad idea to use the name c as an index. Use for example one of the following letters i, j, k, l, m, n.

Also instead of the two if statements you could to convert the current character to uppercase as for example

#include <ctype.h>

//...

char c = toupper( ( unsigned char )string[i] );

Pay attention to that the a record can contain other characters apart from letters. In this case your program will have undefined behavior.

You could define an array of valid letters like for example

const char *letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

and then write

char c = toupper( ( unsigned char )string[i] );
const char *p = strchr( letters, c );

if ( p != NULL ) ++count[p - letters];

//...

Upvotes: 2

Tyler
Tyler

Reputation: 955

y = string[c] - 'A';
count[x]++;

You set y to be the index but use x, looks like you just need to replace the x with y to increment the right index

count[y]++;

Upvotes: 1

Related Questions