#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <ctype.h>
#include "CPstring.h"

// count # of lines, # chars, # words in input file
// written: 7/19/94
// by:      Owen Astrachan
//
// reads input file one char at time, uses state-machine like
// method for determining 'word-hood'

// revised: use <string> instead of "CPstring.h"

struct FileStats
{
    string filename;           // name of file
    long int numLines;         // # of lines in the file
    long int numChars;         // # of characters in the file
    long int numWords;         // # of words in the file
};


void GetStats(FileStats & stats);

int main()
{
    FileStats stats;
    
    cout << "enter name of input file: ";
    cin >> stats.filename;

    GetStats(stats);
        
    cout << "lines = "  << stats.numLines
         << " chars = " << stats.numChars
         << " words = " << stats.numWords << endl;
    return 0;
}

void GetStats(FileStats & stats)
// precondition: stats.filename corresponds to a text file
// postcondition: data members numLines, numChars, numWords reflect # of
//                lines, chars, words in the file stats.filename  
{
    ifstream input( stats.filename.c_str() );		// convert string to c_string
    stats.numLines = stats.numChars = stats.numWords = 0;

    char ch;
    bool inWord = false;           // initially not in word
    while (input.get(ch))          // reading char succeeded
    {
        stats.numChars++;
        if ('\n' == ch)
        {
            stats.numLines++;
        }
        if (isspace(ch))
        {
            if (inWord)             // just finished reading a word
            {
                stats.numWords++;
                inWord = false;    
            }
        }
        else
        {
            inWord = true;          // must be in a word
        }
    }
    if (inWord)                     // word being read when file ended?
    {
        stats.numWords++;
    }
}

