0

我正在编写一个代码,我应该在其中找到字符串中的单词数,因为我知道每个单词都可以由 AZ(或 az)以外的任何字符分隔。我写的代码只有在句首没有标点符号的情况下才能正常工作。但是,当句子以引号等标点符号开头时,麻烦就来了(即“仅连接。”结果将显示 3 个单词而不是 2 个单词)。我正在使用 Dev-C++ 在 C++ 中编程。您的帮助将不胜感激。我的代码如下:

#include <cstring>
#include <iostream>
#include <conio.h>
#include <ctype.h>

using namespace std;

int getline();   //scope
int all_words(char prose[]);  //scope

int main()
{
   getline();
   system ("Pause");
   return 0;
}


int getline()
{
    char prose[600];
    cout << "Enter a sentence: ";

    cin.getline (prose, 600); 
    all_words(prose);
    return 0;
}


int all_words(char prose[])
{ int y, i=0, k=0; int count_words=0; char array_words[600], c;

    do
     {

        y=prose[i++];
        if (ispunct(y))  //skeep the punctuation
         i++;

         if ((y<65 && isspace(y)) || (y<65 && ispunct(y)))     //Case where we meet spacial character or punctuation follwed by space

          count_words++;   //count words

         if (ispunct(y))  //skeep the punctuation
           i++;

    }while (y); //till we have a character

    cout <<endl<<" here is the number of words  "<< count_words <<endl;

   return 0; 

 }



 ***********************************Output******************************
  Enter a sentence: "Only connect!"

  here is the number of words  3

  Press any key to continue . . .
4

2 回答 2

2

我认为你需要重新考虑你的算法。在我的脑海中,我可能会这样做:

  • 循环而不是字符串的结尾
    • 跳过所有非字母字符 ( while (!std::isalpha))
    • 跳过所有字母字符 ( while (std::isalpha))
    • 增加字数计数器

记得在这些内部循环中检查字符串的结尾。

于 2012-09-11T09:25:43.143 回答
0

第一的

if (ispunct(y))

在第一个引号中,您增加了计数器 i,但 var y 仍然包含“,这是产生第二个条件为真。最后一个”为您提供 count_words++ 的额外增量;

if ((y<65 && isspace(y)) || (y<65 && ispunct(y)))

无论如何,您的任务只是将字符串拆分为标记并计算它们。示例解决方案可以在这里找到

于 2012-09-11T09:51:20.267 回答