RocketKatz
RocketKatz

Reputation: 39

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

how can I print a single word from a string in each line with the number of characters right next to it and the average of the characters together? I'm suppose to use a string member function to convert the object into a c string. The function countWords accepts the c string and returns an int. The function is suppose to read in each word and their lengths including the average of characters. I have done how much words are in the string except I don't know how continue the rest.

For example: super great cannon boys

super 5

great 5

cannon 6

boys 4

average of characters: 5

This is my program so 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 than " <<size-1<<" characters."<<endl;
    cin.getline(word, size);
    cout <<"There are "<<countWords(word)<<" words in the sentence."<<endl;

    return 0;
}

int countWords(char *sentence)
{
    int words= 1;
    while(*sentence != '\0')
    {
        if(*sentence == ' ')
            words++;
        sentence++;
    }
    return words;
}

Upvotes: 1

Views: 4843

Answers (4)

Serge Ballesta
Serge Ballesta

Reputation: 148880

This should not be far from you requirements - I only did minimal modification to your present code.

Limits :

  • you'd better use

    string line;
    getline(cin, line);
    

    to read the line to be able to accept lines of any size

  • my present code assumes

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

    it should be improved to cope with extra spaces, but I leave that to you as an 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 than " <<size-1<<" characters."<<endl;
cin.getline(word, size);
cout <<"There are "<<countWords(word, average)<<" words in the sentence."<<endl;
cout << "Average of the 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 is :

Enter words less than 79 characters.
super great cannon boys
super 5
great 5
cannon 6
boys 4
There are 4 words in the sentence.
Average of the sentence 5

Upvotes: 0

mike
mike

Reputation: 41

Going along the lines of what you already have:

You could define a countCharacters function, like your countWords:

int countCharacters(char *sentence)
{
  int i;
  char word[size];
  for(i = 0; sentence[i] != ' '; i++) //iterate via index
  {
    word[i] = sentence[i];   //save the current word
    i++;
  }
  cout <<word<< <<i<<endl; //print word & number of chars
  return i;
}

which you can call inside your countWords function

int countWords(char *sentence)
{
  int words = 1;
  for(int i; sentence[i] != '\0';) //again this for loop, but without
                                   //increasing i automatically
  {
     if(sentence[i] == ' ') {
       i += countCharacters(sentence[++i]);  //move i one forward to skip
                                             // the space, and then move 
                                             // i with the amount of 
                                             // characters we just counted
       words++;                              
     }
     else i++;
  }
  return words;
}

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490098

Unless this is something like homework that prohibits doing so, you almost certainly want to use std::string along with the version of std::getline that works with a std::string instead of a raw buffer of char:

std::string s;
std::getline(std::cin, s);

Then you can count the words by stuffing the line into a std::istringstream, and reading words out of there:

std::istringstream buffer(s);
auto word_count = std::count(std::istream_iterator<std::string>(s), 
                             std::istream_iterator<std::string());

To print out the words and their lengths as you go, you could (for example) use std::for_each instead:

int count = 0;
std::for_each(std::istream_iterator<std::string>(s),
              std::istream_iterator<std::string>(),
              [&](std::string const &s) { 
                  std::cout << s << " " << s.size();
                  ++count;});

Upvotes: 1

Krab
Krab

Reputation: 6756

You can inspire here. Basically use std::getline to read from std::cin to std::string.

#include <iostream>
#include <string>
#include <cctype>

inline void printWordInfo(std::string& word) {

    std::cout << "WORD: " << word << ", CHARS: " << word.length() << std::endl;

}

void printInfo(std::string& line) {

    bool space = false;
    int words = 0;
    int chars = 0;
    std::string current_word;


    for(std::string::iterator it = line.begin(); it != line.end(); ++it) {

        char c = *it;

        if (isspace(c)) {

            if (!space) {

                printWordInfo(current_word);
                current_word.clear();
                space = true;
                words++;

            }
        }
        else {

            space = false;
            chars++;
            current_word.push_back(c);

        }

    }

    if (current_word.length()) {

        words++;
        printWordInfo(current_word);

    }

    if (words) {

        std::cout << "AVERAGE:" << (double)chars/words << std::endl;

    }

}

int main(int argc, char * argv[]) {

    std::string line;

    std::getline(std::cin, line);

    printInfo(line);

    return 0;

}

Upvotes: 0

Related Questions