Search code examples
cwordscounting

Counting the number of words using C from a text file


Hey I have been trying to count the number of words in my text file, to load up a bunch of words for a Hangman game, from C but I am hitting a brick wall. This piece of code I am using is supposed I am using this piece of code;

FILE *infile;
        FILE *infile;
char buffer[MAXWORD];
int iwant, nwords; 
iwant = rand() %nwords;

// Open the file

infile = fopen("words.txt", "r");

// If the file cannot be opened

if (infile ==NULL) {

    printf("The file can not be opened!\n");
    exit(1);
}

// The Word count

while (fscanf(infile, "%s", buffer) == 1) {

    ++nwords;
}

printf("There are %i words. \n", nwords);

    fclose(infile);
}

If anyone has anyone has any suggestions on how to fix this I would be very grateful.

The text file has 1 word per line, with 850 words.

Applied the buffer suggestion, however the word count still came out at 1606419282.

The correction of putting

    int nwords = 0; 

Worked!! Thank you very much!


Solution

  • The variable nwords is never initialized. You cannot assume it to start out as zero.

    If it were, you'd get a crash ("divide by zero") on the next line, whose purpose eludes me:

    iwant = rand() %nwords;
    

    So, replace

    int iwant, nwords; 
    iwant = rand() %nwords;
    

    by

    int nwords = 0;