#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
Recommended Answers
Jump to PostClarify "it does not run". Does it seg fault, or is it getting "stuck" (appears to be doing nothing), or something else?
Jump to PostJust start with some standard debugging. Comment out the entire code and run it. If that is successful, uncomment out a little and run it again, uncomment a little more and run it again, etc. until you get an error. After doing that you will know in what line of …
Jump to Postwithout trying to understand the logic i can tell u a few things ..
> change 'main' to 'int main'
>
change
nWords = numWordsInFile( textFile, nWords);
to
only
numWordsInFile( textFile, nWords);
&
int numWordsInFile( ifstream &in, int &nWords)
to
void numWordsInFile( ifstream &in, int &nWords);as …
All 9 Replies
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.