Hi! I am working on a program to count the number of characters and words in a text file. The counting characters portion works, but my countWords function displays '0'. I built the countWords function on the basis of my countChar function, but since it's returning zero I'm not sure whether there's something still stored in the input stream that I need to clear, or maybe I'm not passing the correct information? I realize that after I get a number, I may need to do some +1 or -1 to bridge the relationship between spaces counted and words. Any hint is greatly appreciated.
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
void problems(char*);
void countChars(ifstream&, char*);
void countWords(ifstream&, char*);
int main(void)
{
const char path[]={"D:\\filepath\\"};
char fileName[32];
char nameWithPath[81];
int counter=0;
cout<<"Enter the input file name: ";
cin>>fileName;
strcat(strcpy(nameWithPath,path),fileName);
ifstream inFile;
inFile.open(nameWithPath);
if (!inFile.good())
problems(nameWithPath);
countChars(inFile, nameWithPath);
countWords(inFile, nameWithPath);
inFile.close();
return 0;
}
void problems(char* file)
{
cerr<<"Problems opening file: "<<file<<endl;
exit(EXIT_FAILURE);
}
void countChars(ifstream& fileName, char* f)
{
char c;
int charCount=0;
while(!fileName.eof())
{
c = fileName.get();
if(c != '\n')
++charCount;
}
cout<<"Number of characters: "<<charCount<<endl;
}
void countWords(ifstream& fileName, char* i)
{
char s;
int wordCount=0;
while(!fileName.eof())
{
s = fileName.get();
if(s == ' ')
++wordCount;
}
cout<<"Number of words: "<<wordCount<<endl;
}