C程序计算函数内带指针的单词数

时间:2015-03-25 17:37:56

标签: c function pointers prototype

我在这里有这个代码块:我想要做的是用指针转换带有for循环和索引[i]的部分。

int main()
{ int i;
  int nwords;

    display_name();
    while (TRUE)
    {   printf("\nEnter a phrase :");
        gets(text);
        if (isEmpty(text))
            return 0;
        //  to be replaced in a function int wordcount(); - START  //
        nwords=0;
        for (i=0; text[i] ; i++)
            if (text[i]==' ' && text[i+1]!=' ')
                nwords++;
        nwords++;
        printf("Text contains %d words\n",nwords);

所以我做到了,直到这里工作正常:

int main()
{ int i;
  int nwords;

    display_name();
    while (TRUE)
    {   printf("\nEnter a phrase :");
        gets_s(text);
        if (isEmpty(text))
            return 0;
        //  to be replaced in a function int wordcount(); - START  //
        nwords = 0;
        p = text;
        for (; *p != '\0'; p++)
            if (*p == ' ' && *p + 1 != ' ')
                nwords++;

        nwords++;
        printf("Text contains %d words\n",nwords);

但我的问题是如何将此代码放在函数wordcount()中,然后从main()调用它?我把代码放在这样的函数中:

int wordcount(char *p){
    char text[256] ;
    int nwords;
    nwords = 0;

    p = text;
    for (; *p != '\0'; p++)
        if (*p == ' ' && *p + 1 != ' ')
            nwords++;
    return nwords;
}

和函数的原型:

int wordcount(char *p);

我称之为这样,但它不计算单词,只打印0&#39。

int main()
{ int i;
  int nwords;

    display_name();
    while (TRUE)
    {   printf("\nEnter a phrase :");
        gets_s(text);
        if (isEmpty(text))
            return 0;
        //  to be replaced in a function int wordcount(); - START  //

        nwords = wordcount(text);
        printf("Text contains %d words\n",nwords);


Student Name : Rasmus Lerdorf
Enter a phrase :asd
Text contains 0 words

Enter a phrase :asdasd
Text contains 0 words

Enter a phrase :asd asdasd
Text contains 0 words

Enter a phrase :asd as as
Text contains 0 words

Enter a phrase :

2 个答案:

答案 0 :(得分:1)

OP方法本质上是有问题的。 (它假设单词存在于输入的第一个中)
例如,要改进如下。

int wordcount(const char *p){
    char prev = ' ';
    int nwords = 0;

    while(*p){
        if(isspace(prev) && !isspace(*p)){//isspace in <ctype.h>
            ++nwords;
        }
        prev = *p++;
    }
    return nwords;
}

答案 1 :(得分:0)

int wordcount(char *text){   // here the pointer to the text is to be passed
char *p;  // no need to declare text again 
int nwords;
nwords = 0;

p = text;    
for (; *p != '\0'; p++)
    if (*p == ' ' && *p + 1 != ' ')
        nwords++;
return nwords;
}

我希望现在能够正常工作