cfilelogicgetc

Read a file and print the first letter of each word


I need to read a file and then print the first letter of each word in lowercase and their position in the file. I made this code but it's not working and i don't know why.

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

int isLetterOrNumber(int c)
{
    if (((c >= 48) && (c <= 57)) || ((c >= 97) && (c <= 122)))
        return 1;
    else
        return 0;
}


int main()
{
    int position, c, pc;

    position = 0;
    FILE *file = fopen("text.txt", "r");
    if (! file){
        printf("Failed to open text.txt.\n");
        return 1;
    }

    while ((c = fgetc(file)) != EOF){
        if (position == 0){
            if (isLetterOrNumber(c)){
                printf("%c %d", c, position);
                position++;
            }
            break;
        }

        pc = fseek(file, -1, SEEK_CUR);
        c = tolower(c);
        pc = tolower(pc);

        if (isLetterOrNumber(c)){
            if (isLetterOrNumber(pc)){
                printf("%c %d", c, position);
                position++;
           }
        }
    }
}

Im trying to verify if the current character and the previous character is a letter or number and then I print it alongside its position in the text.

The file that i need to read is a really big book, it has a lot of characters that are not numbers or letters and i think that im missing something that has to do with that... i'm not sure


Solution

  • There's a few issues with the code you have provided;

    The break statement in the first if block will cause the loop to terminate immediately after printing the first letter, even if there are more letters in the file. This means that only the first letter of the file will be processed and printed.

    The fseek function returns an int, not a character. The variable pc should be declared as an int, and its value should be assigned using fgetc instead.

    The pc and c variables are being passed to tolower incorrectly. The tolower function takes a single int argument representing a character, but the code is passing in the pc and c variables directly. Instead, the value returned by fgetc should be passed to tolower.

    The isLetterOrNumber function does not recognize uppercase letters as valid letters, so it will not correctly handle capitalized words in the file.

    #include <stdio.h>
    #include <ctype.h>
    int main()
    {
    int position = 0;
    int c, prev_c = ' ';
    
    FILE *file = fopen("text.txt", "r");
    if (!file) {
        printf("Failed to open text.txt.\n");
        return 1;
    }
    
    while ((c = fgetc(file)) != EOF) {
        position++;
        if (isalpha(c) && (prev_c == ' ' || position == 1)) {
            printf("%c %d\n", tolower(c), position);
        }
        prev_c = c;
    }
    
    fclose(file);
    return 0;
    

    }