简体   繁体   English

C ++一次打印字符串一个单词,计算字符数和平均字符数

[英]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 ac string. 我想使用字符串成员函数将对象转换为ac字符串。 The function countWords accepts the c string and returns an int. 函数countWords接受c字符串并返回一个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 超级5

great 5 很棒5

cannon 6 大炮6

boys 4 男孩4

average of characters: 5 平均字符数: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;
}

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用的版本一起std::getline与一个工作std::string代替焦炭的原始缓冲区:

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中并从此处读取单词来对单词进行计数:

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: 要随便打印出单词及其长度,可以(例如)使用std::for_each代替:

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;});

You can inspire here. 您可以在这里激发灵感。 Basically use std::getline to read from std::cin to std::string . 基本上使用std::getlinestd::cin读取到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;

}

Going along the lines of what you already have: 按照现有的路线:

You could define a countCharacters function, like your countWords: 您可以定义一个countCharacters函数,例如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 您可以在countWords函数中调用

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;
}

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 2个字之间的一个空格

    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 输入: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM