2012-09-11 27 views
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 . . . 
+0

对你的问题回答[1]。 [1]:http://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c –

回答

2

我认为你需要重新考虑你的算法。我的头顶,我可能会做这样的事情:

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

记住要检查结束这些内部循环中的字符串也是如此。

0

首先

if (ispunct(y)) 

在第一个引号,你已经我递增计数器,但无功ÿ仍然含有“这是产生第二个条件为真最后一个”给你额外的增量count_words ++;

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

无论如何,你的任务只是将字符串拆分为令牌并对它们进行计数。示例解决方案可以在这里找到here

相关问题