Average word Length

Ive been asked to write a program that reads a text file and counts the number of characters used, counts the number of words used and then divides the two sums to obtain the average word length of the document.
I have the amount of characters... almost I cant figure out how to omit the symbols, the spaces and the beginning or ending of a line. and i think that the condition for the words would be similar but defined as a string? I dont know I'm really stuck and any help at all would be greatly appreciated

#include <iostream>
#include <fstream>

using namespace std;

int main( )
{
ifstream infile;
ofstream outfile;

infile.open("hw4pr11input.txt");
if (infile.fail())
{
cout << "input file could not be opened" << endl;
system("pause");
exit(1);
}
int word_number=0, character_number=0;
char letter;
double average;

while (!infile.eof())
{
infile.get(letter);
cout << letter;
character_number++;
}


cout << "the total charecter count is " << character_number << endl;
cout << "the total word count is " << word_number << endl;

cout << "the average word length is " << average << endl;

infile.close();


system("Pause");
return 0;
}

I changed it a little and now it crashes right before line 37

#include <iostream>
#include <fstream>

using namespace std;

int main( )
{
ifstream infile;
ofstream outfile;

infile.open("hw4pr11input.txt");
if (infile.fail())
{
cout << "input file could not be opened" << endl;
system("pause");
exit(1);
}
int word_count=0, character_count=0;
char letter;
double average;
cout.precision(2);
cout.setf(ios::showpoint);
cout.setf(ios::fixed);

while (!infile.eof())
{
infile.get(letter);
cout << letter;
character_count++;

}


cout << "the total charecter count is " << character_count << endl;

cout << "the total word count is " << word_count << endl;

average = character_count/word_count; // crashes here

cout << "the average word length is " << average << endl;


infile.close();


system("Pause");
return 0;
}

Last edited on
closed account (2b5z8vqX)
I changed it a little and now it crashes right before line 37

The variable word_count is never modified throughout the program so the value remains zero (what it was initialized to in its definition). When you attempt to perform a division operation on (two int values) character_count and word_count (always zero), the result is undefined so your program crashes.

http://en.wikipedia.org/wiki/Division_by_zero

Your program would end without error if both operands of the division operator were converted to a flloating-point type.

Also, please use the code tags and post formatted code.
Last edited on
ok divide by zero makes sense. Sorry for my not knowing but i would rather ask then keep doing things wrong, How do I use the code tags and post formatted code?
Topic archived. No new replies allowed.