Counting words by character
OK new to C++ and want to learn it, having problem with
code that inputs file and counts the words in the file. I am doing this by character, I know I can do it by string easier! just looking for
direction.
File opens, Loop works, count works but is not correct?
As I parse a page do I have to make any other excludes for line breaks, \n or other ......
Code:
#include <cstdlib>
#include <iostream>
#include <cassert>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int wordCount;
char prevChar;
char currChar;
ifstream inFile;
string fileName;
cout << "Enter the input file name (quit to exit): ";
cin >> fileName;
while (fileName != "quit"){
inFile.open(fileName.c_str());
assert(inFile);
wordCount = 0;
inFile.get(prevChar);
inFile.get(currChar);
while(inFile.get() != '\n') {
if (currChar == ' ' || prevChar != ' ')
wordCount++;
prevChar = currChar;
inFile.get(currChar);
}
cout << "There are " << wordCount << " words in this "
<< fileName << endl << endl;
inFile.close();
inFile.clear();
cout << '\a';
cout << "Enter the input file name (quit to exit): ";
cin >> fileName;
}
system("PAUSE");
return EXIT_SUCCESS;
}