JohnMcG gave an excellent answer to your immediate problem, but there's other things to be concerned about that won't fit into a comment. Remember that a character array can hold a string one char smaller than its length, so use MAX_WORD_LENGTH + 1
for the length. I'd also suggest initializing those strings to the null string, so that there's a '\0' at the beginning of each string before the loop.
Is there any reliable length limit on the words? If not, the problem becomes more involved with C-style strings (although not C++ strings). You'll have to allocate pointers (as you have), and reallocate them as necessary while reading character by character. Fiddly stuff, and this is one case where I'd recommend using malloc()
/free()
/realloc()
rather than C++ memory management.
I assume you're already aware that you're reading words and not lines. Your array name suggests that, but it's a common error among students.
You didn't declare i
in the for
statement, so it's a variable with scope outside, which brings up the possibility that you might be using its value later. If so, remember that .eof()
doesn't mean the program has run out of input, it means the program has tried to read off the end of the file. If the file ends in a whitespace character (like '\n'), it will read the last word and then increment i
and read nothing. If it doesn't, it will try to read past the end of file while reading the last word, and won't increment i
again.
If you need a count of words, then, you need to have initialized the memory, as mentioned above, and you need to check whether words[i]
is empty or not (strlen()
is overkill, check the first character for \0
).