#include <fstream>
#include <iostream>
#include <string>
using namespace std;
string getFileName();
int numCharsInFile( ifstream &in, int &nLines );
int numWordsInFile( ifstream &in, int &nWords );
main ()
{
int nLines,
nChar,
avgCPL,
nWords;
ifstream textFile;
string fileName;
fileName = getFileName();
textFile.open(fileName.c_str());
if(!textFile.is_open())
{
cerr << "Cannot open file: " << fileName << endl << endl;
exit (0);
}
nWords = numWordsInFile( textFile, nWords);
nChar = numCharsInFile( textFile, nLines );
avgCPL = nChar / nLines;
cout << "Number of Words: " << fileName<< " is = " << nWords << endl;
cout << "Number of characters: " << fileName<< " is = " << nChar << endl;
cout << "Number of lines: " << fileName<< " is = " << nLines<<endl;
cout << "Average characters per line: "<< fileName << " is: " << avgCPL << endl;
system("pause");
textFile.close();
}
string getFileName()
{
string fileName;
cout << "Please enter file name of the input text file (i.e. including the path): ";
cin >> fileName;
cout << endl;
return fileName;
}
int numCharsInFile(ifstream &in,int &nLines )
{
int nChar = 0;
char ch;
nLines = 0;
while (in.get(ch))
{
if (ch != ' ' )
{
if(ch != '\n')
nChar++;
else
{
nLines++;
}
}
}
return nChar;
}
int numWordsInFile( ifstream &in, int &nWords)
{
in.clear();
in.seekg(0, ios_base::beg);
int numWords = 0 ;
char ch;
while (in.get(ch))
{
if ( ch == ' ' || ch == '\n' || ch == '\t' )
numWords++;
}
return numWords;
}
VIcissitude24 0 Newbie Poster
plgriffith 0 Junior Poster
VIcissitude24 0 Newbie Poster
plgriffith 0 Junior Poster
VIcissitude24 0 Newbie Poster
jobob64 0 Newbie Poster
jobob64 0 Newbie Poster
Agni 370 Practically a Master Poster Featured Poster
VIcissitude24 0 Newbie Poster
superjacent 1 Junior Poster in Training
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.