I am trying to count uppercase and lowercase letters, the number of digits, and the number of words in an input file. I have completed this, however, my word count is off by one. There are 52 words in the input file, but my count is 53. What would be causing this? All of the others (uppercase, lowercase, and digit) are all correct...
Here's what I have:
using namespace std;
int main()
{
fstream inFile;
fstream outFile;
string fileName("");
string destName("");
char c = 0;
///////string wrdRev("");/////////
int numCount = 0;
int capCount = 0;
int lowCount = 0;
int wordCount = 0;
cout << "Please enter file name: ";
getline(cin, fileName);
cout << endl;
inFile.open(fileName, ios::in);
if (inFile.good() != true) {
cout << "File does not exist!\n" << endl;
return 0;
}
else{
reverse(fileName.begin(), fileName.end());
destName += fileName;
}
outFile.open(destName, ios::in);
if (outFile.good() == true){
cout << "File '" << destName << "' already exists!\n" << endl;
return 0;
}
else {
outFile.clear();
outFile.open(destName, ios::out);
while(inFile.good() != false){
inFile.get(c);
if(isupper(c)){
capCount++;
}
else if(islower(c)){
lowCount++;
}
else if(isdigit(c)){
numCount++;
}
else if(isspace(c)){
wordCount++;
}
}
outFile << "There are " << capCount << " uppercase letters." << endl;
outFile << "There are " << lowCount << " lowercse letters." << endl;
outFile << "There are " << numCount << " numbers." << endl;
outFile << "There are " << wordCount << " words." << endl;
}
inFile.close();
outFile.close();
return 0;
}
Any help would be appreciated. Thank you.
ios::good()
returns true
after reading the last character in file. So you come to the loop body one extra time. That last time the read fails, the character gets unchanged, and because it's apparently a whitespace character the word count is incremented.
You shouldn't generally use this good()
, eof()
etc. as a test for end of input. Do this instead:
while (inFile.get(c)) {
//...
}