user1090530
user1090530

Reputation: 3

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!

Upvotes: 0

Views: 3027

Answers (3)

Gangnus
Gangnus

Reputation: 24464

  1. After reading the first word and whitespace after it, your fscanf RETURNS to input buffer the whitespace. So, the next time you read EMPTY word.
  2. Change proposed:

    fscanf(infile, "%s ", &buffer) // notice the space!!! And & before buffer

    It will throw off ALL whitespace till the next word. It should work.


P.S. Better not use [f]scanf :-)

Upvotes: 0

wolfgang
wolfgang

Reputation: 4953

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;

Upvotes: 1

Martin Beckett
Martin Beckett

Reputation: 96119

So the words are one entry per line?

while (fscanf(infile, "%s", &nwords) == 1); {
    ++nwords;
}

Doesn't do what you think it does. It reads a string in nwords, which isn't a string. If you want to do it like this then you need to allocate a string ie char buffer[XXX] which is long enough to contain the longest lien in your data file and use:

while (fscanf(infile, "%s", buffer) == 1) {
    ++nwords;
}

Upvotes: 2

Related Questions