Hi there, I have been lurking around these forums for awhile, but this is my first post. I'm stuck on an assignment that requires me to determine how many words are in a file by reading one character at a time. I am not allowed to use string to count words, as that was the previous assignment which I have already done succesfully.
My problems are: I am off by 1 on the count, but only in some files, and if I put curly braces around the imbedded if statement, the loop will not quit. Also making me unable to add an else if statement. I beleive if I was able to use the if statements like I want to I could correct the count issue easily.
Here is an example of file1, which should have 7 words, but my program displays as 6.
"
This &%file should!!,...
have exactly 7 words.
"
Here is file5, which my program calculates the correct amount of words, 22.
"
Mr. &%Brown can moo!!,...
'
can you? This file should have several blank lines before the end of the file.
22 words.
"
Code:#include <fstream> #include <iostream> #include <cassert> #include <cstring> using namespace std; int main() { string aString; char prevChar; char currChar; int count = 1; ifstream inFile; cout << "Please enter the name of the file you " << endl; cout << "would like to count: "; cin >> aString; do { if (aString == "Q" || aString == "q") { return 0; } inFile.open(aString.c_str()); assert(inFile); inFile.get(prevChar); inFile.get(currChar); while (inFile) { if (prevChar == ' ' && currChar != ' ') count++; prevChar = currChar; inFile.get(currChar); } inFile.close(); inFile.clear(); cout << "This file has " << count << " words." << endl; cout << prevChar << endl << currChar << endl; count = 1; cout << "***********************" << endl; cout << "Please enter the name of the file you " << endl; cout << "would like to count (Type Q to quit): "; cin >> aString; } while (inFile); return 0; }



LinkBack URL
About LinkBacks


