I have completed half of this program, and i don't know how to do the rest half, I have to submit this by tonight, could anyone please help me out with this?
How would i count the average letters per word in a sentence??
#include <iostream>
#include <string>
using namespace std;
int WordCount(string);
int letterCount(string);
int main()
{
string Mystring;
cout << " Type in the string you would like to use: " << endl;
getline(cin, Mystring); // inputs sentence
cout << " Your string is: " << Mystring << endl;
cout << " The string has " << WordCount(Mystring) << " words " << endl;
cout << " the avg letters per word is " << letterCount(Mystring);
system("pause");
return 0;
}
// counts the words
int WordCount(string Sentence)
{
int length = Sentence.length(); // gets lenght of sentence and assines it to int length
int words = 1;
for (int size = 0; length > size; size++)
{
if (Sentence[size] == ' ' && Sentence[size-1] != ' ')
/*space*/
words++; // ADDS TO words if there is a space
}
if ( Sentence[0] == ' '/*space*/ )
words--;
return words;
}
To get the average number of words per sentence, you need to sum the number of letters in each word then divide by the number of words. Your answer looks very close; I think you just need to subtract spaces as you mentioned before.
I got it! if anyone wants to look at my code, maybe add to it or give any suggestions, be my guest! Cheerz happy coding!
#include <iostream>
#include <string>
using namespace std;
int WordCount(string);
float letterCount(string);
int main()
{
string Mystring;
cout << " Enter a string: ";
getline(cin, Mystring); // inputs sentence
//cout << endl << " Your string is: " << Mystring << endl;
cout << "There are "<< WordCount(Mystring) << " words in that sentence." << endl;
cout << "The average number of letters per word is " << letterCount(Mystring) << endl;
system("pause");
return 0;
}
// counts the words
int WordCount(string Sentence)
{
int length = Sentence.length(); // gets lenght of sentence and assines it to int length
int words = 1;
for (int size = 0; length > size; size++)
{
if (Sentence[size] == ' ' && Sentence[size-1] != ' ')
/*space*/
words++; // ADDS TO words if there is a space
}
if ( Sentence[0] == ' '/*space*/ )
words--;
return words;
}
float letterCount(string sentence)
{
float length = sentence.length(); // gets lenght of sentence and assines it to int length
float avgNumber;
int spaces =0;
float words = 1;
for (int size = 0; length > size; size++)
{
if (sentence[size] == ' ' && sentence[size-1] != ' ')
{/*space*/
words++;
spaces++;// ADDS TO words if there is a space
}
}
if (sentence[0] == ' '/*space*/ )
{ words--;