【问题标题】:C++ print string one word at a time, count characters, and average of charactersC ++一次打印一个单词,计算字符数,平均字符数
【发布时间】:2015-04-25 21:49:30
【问题描述】:

如何从每行的字符串中打印一个单词,并在其旁边显示字符数以及字符的平均值?我想使用字符串成员函数将对象转换为 c 字符串。 countWords 函数接受 c 字符串并返回一个 int。该函数假设读取每个单词及其长度,包括字符的平均值。我已经完成了字符串中有多少单词,除了我不知道如何继续其余的。

例如:超级大炮男孩

超级5

伟大的 5

大炮 6

男孩 4

平均字符数:5

这是我目前的程序:

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

【问题讨论】:

  • 使用索引和for 循环遍历字符串可能比指针算法更简洁易用。
  • @Carcigenicate 使用std::string 并通过for each loop 对其进行迭代更加容易。
  • @NO_NAME 我想他说他需要使用 c 字符串。
  • @Carcigenicate 对不起。 #include &lt;string&gt;把我弄糊涂了。
  • 而不是测试 *sentence == ' ' 你应该测试 isspace(*sentence) 。此外,您可能需要考虑使用标点符号函数 ispunct () 。两者在 ctype.h 中都有原型

标签: c++ string


【解决方案1】:

除非这是禁止这样做的家庭作业,否则您几乎肯定希望使用std::string 以及与std::string 一起使用的std::getline 版本,而不是char 的原始缓冲区:

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

然后您可以通过将行填充到std::istringstream 中来计算单词,然后从那里读取单词:

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

要随时打印出单词及其长度,您可以(例如)改用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;});

【讨论】:

    【解决方案2】:

    这应该与您的要求相差不远 - 我只对您当前的代码进行了少量修改。

    限制:

    • 你最好用

      string line;
      getline(cin, line);
      

      读取行以能够接受任何大小的行

    • 我目前的代码假设

      • 行首或行尾无空格
      • 两个单词之间有一个空格

      应该改进它以应对额外的空间,但我把它留给你作为练习:-)

    代码:

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

    输入:super great cannon boys

    输出是:

    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
    

    【讨论】:

      【解决方案3】:

      您可以在这里激发灵感。基本上使用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;
      
      }
      

      【讨论】:

        【解决方案4】:

        按照你已经拥有的路线:

        您可以定义一个 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;
        }
        

        您可以在 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;
        }
        

        【讨论】:

          猜你喜欢
          • 2014-04-29
          • 1970-01-01
          • 2013-10-21
          • 1970-01-01
          • 2011-11-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多