Count number of words in a text file Is this a good approach or is there some other solution that I am not aware of?

//C++ program to count number of words in text file

#include&lt;fstream&gt;
#include&lt;iostream&gt;
#include&lt;string&gt;
using namespace std;

int main()
{
    ifstream inFile; //Declares a file stream object
    string fileName;
    string word;
    int count = 0;

    cout &lt;&lt; "Please enter the file name ";
    getline(cin,fileName);

    inFile.open(fileName.c_str());

    while(!inFile.eof())
    {               
        inFile &gt;&gt; word; 
        count++;
    }

    cout &lt;&lt; "Number of words in file is " &lt;&lt; count;
    inFile.close();

    cin.get();  
    return 0;
}
Your code has a few problems.


You should learn to not use using namespace std;. It's generally frowned upon.
You should never use while(!inFile.eof()). It's pretty much a guaranteed bug.
You should use standard algorithms when they're applicable (as they are here).
Prefer to fully initialize variables at creation (e.g., pass file name when you create a filestream object).
Generally let the destructor handle destruction (e.g., let the filestream object close when it goes out of scope)1.


I'd also strongly prefer to take command line arguments over prompting for input at run time.

I'd write the code using the standard distance algorithm, something like this:

#include &lt;fstream&gt;
#include &lt;algorithm&gt;
#include &lt;iterator&gt;
#include &lt;iostream&gt;
#include &lt;string&gt;
#include &lt;cstdlib&gt;

int main(int argc, char **argv) {
    if (argc &lt; 2) {
        std::cerr &lt;&lt; "Usage: count_words &lt;infile&gt;\n";
        return EXIT_FAILURE;
    }

    std::ifstream infile(argv[1]);

    std::istream_iterator&lt;std::string&gt; in{ infile }, end;

    std::cout &lt;&lt; "Word count: " &lt;&lt; std::distance(in, end);
}





There are a few cases where it makes sense to manually close a file. For example, if you're moving a file between file systems by copying its content, then deleting the original, you want to do everything you can to ensure the copy completed successfully (including successful closing) before you remove the original. Anything that might destroy the user's data calls for extraordinary measures to assure safety. This isn't one of those cases though.