C++ print string one word at a time, count characters, and average of characters -


how can print single word string in each line number of characters right next , average of characters together? i'm suppose use string member function convert object c string. function countwords accepts c string , returns int. function suppose read in each word , lengths including average of characters. have done how words in string except don't know how continue rest.

for example: super great cannon boys

super 5

great 5

cannon 6

boys 4

average of characters: 5

this program far:

#include <iostream> #include <string> #include <cstring>  using namespace std;  int countwords(char *sentence);  int main() {     const int size=80;     char word[size];     double average=0;     cout<<"enter words less " <<size-1<<" characters."<<endl;     cin.getline(word, size);     cout <<"there "<<countwords(word)<<" words in sentence."<<endl;      return 0; }  int countwords(char *sentence) {     int words= 1;     while(*sentence != '\0')     {         if(*sentence == ' ')             words++;         sentence++;     }     return words; } 

this should not far requirements - did minimal modification present code.

limits :

  • you'd better use

    string line; getline(cin, line); 

    to read line able accept lines of size

  • my present code assumes

    • no spaces @ beginning or end of line
    • one single space between 2 words

    it should improved cope spaces, leave exercise :-)

the code :

#include <iostream> #include <string> #include <cstring>  using namespace std;  int countwords(char *sentence, double& average);  int main() { const int size=80; char word[size]; double average=0; cout<<"enter words less " <<size-1<<" characters."<<endl; cin.getline(word, size); cout <<"there "<<countwords(word, average)<<" words in sentence."<<endl; cout << "average of sentence " << average << endl; return 0; }  int countwords(char *sentence, double& average) { int words= 1; int wordlen; char *word = null; while(*sentence != '\0') {     if(*sentence == ' ') {         words++;         wordlen = sentence - word;         average += wordlen;         *sentence = '\0';         cout << word << " " << wordlen<< endl;           word = null;     }     else if (word == null) word = sentence;     sentence++; } wordlen = sentence - word; average += wordlen; cout << word << " " << wordlen<< endl;   average /= words; return words;  } 

for input : super great cannon boys

output :

enter words less 79 characters. super great cannon boys super 5 great 5 cannon 6 boys 4 there 4 words in sentence. average of sentence 5 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -