finding the average

I wrote this program that works great except for when the avg isn't a whole number. If countWords is 3 and countSent is 2 then the program stops!!! Help!

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
string str;
char ch;
int i;
int countSent, countWords;
float avg;

cout << "Enter sentences, when you are done press Enter: ";
i = 0;

while(ch = cin.get())
{
if(ch != '\n')
{
str[i] = ch;
i++;
}
else
break;

}
i = 0;
countWords = 0;
countSent = 0;

while (str[i] && str[i] != '\n')
{
if(str[i] == ' ')
countWords++;
if(str[i] == '!')
countSent++;
if(str[i] == '?')
countSent++;
if(str[i] == '.')
countSent++;
i++;
}

countWords++;

avg = countWords/countSent;

cout << "The number of sentences entered is " << countSent << endl;
cout << "The number of words typed is " << countWords << endl;
cout << "The average number of words per sentence is " << avg << endl;

return 0;
}
The line

 
avc = countWords / countSent;


performs integer division of countWords by countSent then casts the result to a float.
You need to force floating point division. To do that, you must make sure that either
the divisor or the dividend is floating point to begin with (or both).

 
avg = countWords / (float)countSent;

Still not working after trying to add (float). It works if the average is a whole number but not a fraction. help!!!

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
string str;
char ch;
int i;
int countSent, countWords;
float avg;

cout << "Enter sentences, when you are done press Enter: ";
i = 0;

while(ch = cin.get())
{
if(ch != '\n')
{
str[i] = ch;
i++;
}
else
break;

}
i = 0;
countWords = 0;
countSent = 0;

while (str[i] && str[i] != '\n')
{
if(str[i] == ' ')
countWords++;
if(str[i] == '!')
countSent++;
if(str[i] == '?')
countSent++;
if(str[i] == '.')
countSent++;
i++;
}

countWords++;

avg = countWords/countSent;

cout << "The number of sentences entered is " << countSent << endl;
cout << "The number of words typed is " << countWords << endl;
cout << "The average number of words per sentence is " << avg << endl;

return 0;
}
You produced a fence-post error by doing str[i] = ch. Replace it with str.push_back(ch).
Topic archived. No new replies allowed.