I am making a c++ program that counting the number of words in the text file. Bu
ID: 3544528 • Letter: I
Question
I am making a c++ program that counting the number of words in the text file. But when I run the program. It says there are -858992621 words, which is clealy wrong...
Please help!! heres the code! THANKS!!!
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
string getInputFileName();
int wordsInFile( ifstream &in, int &words );
int main ()
{
int numWords;
ifstream inFile;
string fileName;
fileName = getInputFileName();
inFile.open(fileName.c_str());
if( !inFile.is_open() )
{
cerr << "Cannot open file: " << fileName << endl << endl;
exit (0);
}
numWords = wordsInFile( inFile, numWords);
cout<<"there are "<<numWords<<" words in the file: "<<fileName<<endl;
inFile.close();
}
string getInputFileName()
{
string fName; // fully qualified name of the file
cout << "Please enter the fully qualified name of the " << endl
<< "input text file (i.e. including the path): ";
cin >> fName;
cout << endl;
return fName;
}
int wordsInFile( ifstream &in, int &words )
{
in.clear();
in.seekg(0L, ios::beg);
char ch;
while (in.get(ch))
{
if ( ch==' '||ch==' '||ch==' '||ch==','||ch=='.'||ch==':'||ch=='('||ch==')'||ch=='?'||ch=='!')
words++;
}
return words+1;
}
Explanation / Answer
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
string getInputFileName();
int wordsInFile( ifstream &in, int &words );
int main ()
{
int numWords=0; // u haven't initialized it hence it take garbage value
ifstream inFile;
string fileName;
fileName = getInputFileName();
inFile.open(fileName.c_str());
if( !inFile.is_open() )
{
cerr << "Cannot open file: " << fileName << endl << endl;
exit (0);
}
numWords = wordsInFile( inFile, numWords);
cout<<"there are "<<numWords<<" words in the file: "<<fileName<<endl;
inFile.close();
}
string getInputFileName()
{
string fName; // fully qualified name of the file
cout << "Please enter the fully qualified name of the " << endl
<< "input text file (i.e. including the path): ";
cin >> fName;
cout << endl;
return fName;
}
int wordsInFile( ifstream &in, int &words )
{
in.clear();
in.seekg(0L, ios::beg);
char ch;
while (in.get(ch))
{
if (!( ch==' '||ch==' '||ch==' '||ch==','||ch=='.'||ch==':'||ch=='('||ch==')'||ch=='?'||ch=='!'))
words++;
}
return words+1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.