I wrote a program for counting the number of alphanumeric characters in a text file. However, the number it returns is always larger than the number that online character counters return.
For example, the program will calculate the number of alphanumeric characters in this text:
if these people had strange fads and expected obedience on the most
extraordinary matters they were at least ready to pay for their
eccentricity
to be 162. Running the program again, it’ll say there are 164 characters in the text. Running it again, it’ll say there are 156 characters. Using this online character counter, it seems that the character count ought to be lower than 144 (the online character counter includes spaces as well).
Here is the code:
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main() {
char line[100];
int charcount = 0;
ifstream file("pg1661sample.txt");
while (!file.eof()) {
file.getline(line, 99);
for (int i = 0; i < 100; i++) {
if (isalnum(line[i])) {
charcount++;
}
}
}
cout << endl << "Alphanumeric character count: " << charcount;
cin.get();
return 0;
}
What am I doing wrong?
Try:
Problems with your code:
EOF is not true until you read past the end of file:
It is better to always do this:
The loop is only entered if the getline actually worked.
You are also using a bad version of getline (as lines may be larger than 100 characters).
Try and use the version that works with std::string so it auto expands.
Next you assume the line is exactly 100 characters.
What happedn if the line is only 2 characters long?
Basically you will scan over the data and it will count letters that were from left over from a previous line (if a previous line was longer than the current) or completely random garbage. If you are still useing
file.getline()then you can retrieve the number of characters from a line usingfile.gcount(). If you use the std::getline() then the variablelinewill be the exact size of the line read (line.size()).