Counting words from text file issue

Hello,

I'm a C++ novice and am trying to write a word-counter function that reads from a text file. My code compiles without any errors, but when I run it, the loop doesn't seem to terminate and so the terminal freezes.

It seems to be an issue with the position of 'return words;' on line 12. At first I had it inside the while loop, but then it always returned 0 and I realised it was because the while loop would stop right away before going through the whole file. So I moved it outside of the while loop, and it makes sense in my head that it should be there, but now I'm running into this problem. Any insight would be greatly appreciated.

Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
int getNWords(string filename)
{
  int words=0;
  char c;
  ifstream in_stream;
  in_stream.open(filename.c_str());

  while (!in_stream.eof()) {
    if (c == ' ')
      words++;
  }
  return words;
}
will c ever be ' ' ??
I dont see any where you read from the file.
Last edited on
I opened it in line 6 with in_stream.open, and the file is the function argument. I used the same method to read from a file for line-counting function elsewhere in the program, so I know it works. And for the c == ' ', I guess that was another point where I wasn't totally sure about my code because I wasn't sure how to get the program to iterate through every character to see if it's a space.
If I'm understanding correctly, then what you're doing is going to through the file, counting up how many words there are, if the program finds a white space then you simply increment the word variable by 1 and then continue until you reach the end of the file.

What I think would be a good idea is to use the isspace function to detects whitespaces as you're reading through the file. Also remember to include the cctype header file and that this function only pertains to char data types.
Last edited on
why your loop runs for ever.

When you open a file to read, the file pointer is set to the begininning of the file. when every character is read, the pointer moves to the next position. Its by moving to this position upon the reading of characters that the pointer finally meets the end of the file and returns EOF .

In a nutshell, if you dont read from the file, the pointer does not move to the next position of the file. Hence you never attain EOF.

That is why i asked for where you read from the file.
Since you dont read, in_stream.eof() is never met.

In line 6, you open the file but then you have to read a character from it into c.

add the line in_stream>>c between line 8 and 9.
Topic archived. No new replies allowed.