I have to write a program that requests a file name from the user and then counts all of the words in the file. The hypothetical file has 55 words in it, but my program counts 56 words.
Every change I've tried making to my code has only gotten me farther from the correct answer, either resulting in 0 words or causing it to become an infinite loop. I'm seriously stuck on where the extra word/character is coming from, so I was hoping someone might see an error that I'm missing.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char filename[20];
cout << "Enter a file name: ";
cin >> filename;
ifstream fin;
fin.open(filename);
if (fin.fail())
{
exit(1);
}
char next;
int word = 0;
while (fin)
{
fin.get(next);
if (next == ' ' || next == '\n')
word++;
}
fin.close();
cout << "The file contains " << word << " words.";
return 0;
}
I debugged and modified your code. Here is my version:
Two tips:
ifstreamread the last char of file, it will count it twice. Because the first time ifstream reads it,eof()will not be true. The second time ifstream reads it,eof()will be true. But thenextvariable keeps the last value. So it counts twice. Solution is when ifstream read a char, we check it again byfin.fail().BTW, my code is based on your version. I didn't handle the mixed space or newline.
Docs about
eof():