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;
}