Reputation: 1
I'm trying to count the number of characters and lines in a file using the following function.
void characterCount(ifstream& inf, string fName, int length [])
{
int charNum = 0;
int lineNum = 0;
char character;
inf.get(character);
while (!inf.eof())
{
// counts a line when an endline character is counted
if (character = '\n')
++lineNum;
charNum++;
inf.get(character);
if (character = EOF)
break;
}
inf.close();
inf.clear();
wordTabulate(inf, charNum, lineNum, length, fName);
}
void wordTabulate(ifstream& inf, int charNum, int lineNum, int count [], string fName)
{
inf.open(fName);
string word;
while (inf >> word)
{
cout << word;
count[word.size()]++;
}
inf.close();
inf.clear();
inf.open(fName);
output (inf, charNum, lineNum, count);
}
Unfortunately it will only count 1 line, 1 character, and will not classify the words based on size. All the other functions I wrote for it seem to work fine. I've tried a variety of different things for the character counter but nothing seems to work. Any help you could provide would be greatly appreciated.
Below I've added the output function. I'm sure there is a better way to output from an array but I'm not too worried about that right now.
void output(ifstream& inf, int charNum, int lineNum, int count [])
{
int words = 0;
cout << "Characters: " << charNum << endl;
words = totalWord(count);
cout << "Words: " << words << endl;
cout << "Paragraphs: " << lineNum << endl;
cout << "Analysis of Words: " << endl;
cout << "Size 1 2 3 4 5 6 7 8 9 10+" << endl;
cout << "#Words" << count [2], count [3], count [4], count [5],
count [6], count [7], count [8], count [9], count [10];
}
Here is the open file function which I believe is the culprit.
bool fileOpen(string fileName, ifstream& inf, int wordTypes [])
{
int charNum = 0;
int lineNum = 0;
cout << "File? >" << endl; // asks for file name
cin >> fileName;
// opens file and indicates if file can be opened
bool Repeat ();
{
inf.open(fileName.c_str());
if (inf.is_open())
{
return true;
}
if (!inf.is_open())
{
return false;
}
}
}
Upvotes: 0
Views: 11158
Reputation: 154045
The problem in your first loop is that you don't read a character in the loop and also that you try to use eof()
as an end condition. Neither works. You always need to check after reading that you successfully read the entity and eof()
is not the condition you are looking for. Your loop should have a condition like this:
for (char value; in.get(value); ) {
...
}
The above loop will read through all the characters in the file and avoid any need to treat EOF
special. That said, I always love constructive solutions to the problem. Here is mine:
void count(std::istream& in, int& chars, int& words, int& lines)
{
bool word(false);
std::for_each(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>(),
[&](unsigned char c) {
word = !std::isspace((++chars, c))
&& (word || ++words);
c == '\n' && ++lines; });
}
Upvotes: 2