Hi,
I have written a program that counts number of words in a text file as shown below.
Code:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char string[1000]; //to hold the text read out of file
char *tokenPtr;//pointer is used to set aside a momory address to store the first token
int count_word;
FILE *f;
f = fopen("output.txt", "r");
count_word = 0;
fgets(string,1000,f);
tokenPtr = strtok(string, " !@#$%^&*()_+=-{}[]|\"':;<,>.?/~`");// string, delimiters used to specify the boundary between regions
while(tokenPtr != NULL) // stop at NULL
{
tokenPtr = strtok(NULL, " !@#$%^&*()_+=-{}[]|\"':;<,>.?/~`");
count_word++;
}
printf("\n# of words: %d\n", count_word);
}
fclose(f);
return 0;
}
How to get program to correctly print out that # of words is 0 when the text file is empty? I was thinking of either checking of first character is EOF (by way of fgetc) or by checking if string[0] is a null, but I somehow can't get it working.... as of now, program always incorrectly tell me text file has 1 word when the text file is empty.
Thanks for all help in advance!!