patterncppModerate
Count number of words in a text file
Viewed 0 times
numberfilewordstextcount
Problem
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
#include
#include
using namespace std;
int main()
{
ifstream inFile; //Declares a file stream object
string fileName;
string word;
int count = 0;
cout > word;
count++;
}
cout << "Number of words in file is " << count;
inFile.close();
cin.get();
return 0;
}Solution
Your code has a few problems.
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
- 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
#include
#include
#include
#include
#include
int main(int argc, char **argv) {
if (argc \n";
return EXIT_FAILURE;
}
std::ifstream infile(argv[1]);
std::istream_iterator in{ infile }, end;
std::cout << "Word count: " << 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.
Code Snippets
#include <fstream>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <string>
#include <cstdlib>
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "Usage: count_words <infile>\n";
return EXIT_FAILURE;
}
std::ifstream infile(argv[1]);
std::istream_iterator<std::string> in{ infile }, end;
std::cout << "Word count: " << std::distance(in, end);
}Context
StackExchange Code Review Q#49038, answer score: 19
Revisions (0)
No revisions yet.