#include <iostream> // cout, endl
#include <iomanip> // setw
#include <vector> // vector
#include <string> // string
#include <fstream> // ifstream
#include <sstream> // stringstream
#include <algorithm> // for_each
// Print the counts and filename formatted
void print_results(size_t char_count, size_t word_count,
size_t line_count, const std::string& filename)
{
std::cout << std::setw(10) << line_count;
std::cout << std::setw(10) << word_count;
std::cout << std::setw(10) << char_count;
std::cout << " " << filename << std::endl;
}
void CountLWC(const std::string& filename)
{
// Open the text file for reading
std::ifstream infile(filename.c_str());
if (!infile.is_open())
std::cout << "Can't open file: " << filename << std::endl;
else
{
// Initialize the counters
size_t char_count = 0; // characters
size_t word_count = 0; // words
size_t line_count = 0; // lines
// For each line in the file
while (!infile.eof())
{
// Read an entire line from the file
std::string line;
if (std::getline(infile, line).eof())
break;
// Increment lines and characters
line_count++;
char_count += line.size() + 1; // Account for newline
// Count words in the line
std::string word;
std::stringstream words(line);
while (!words.eof())
{
words >> word; // Try to read next word
if (!words.fail()) // If there was a next word
word_count++; // count it
}
}
// Display the results from this file
print_results(char_count, word_count, line_count, filename);
}
}
int main(int argc, char *argv[])
{
// Need at least one file
if (argc < 2)
{
std::cout << "Usage: mywc <textfile1> <textfile2> ...\n";
return 1;
}
// Count the chars, words, and lines and print them
std::for_each(argv + 1, argv + argc, CountLWC);
return 0;
}