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

C program counting number of words with pointers inside a function

我这里有这段代码:我想做的是用 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 != '[=11=]'; 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 != '[=12=]'; p++)
        if (*p == ' ' && *p + 1 != ' ')
            nwords++;
    return nwords;
}

以及函数的原型:

int wordcount(char *p);

我这样称呼它,但它不计算字数,只打印 0。

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 :
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 != '[=10=]'; p++)
    if (*p == ' ' && *p + 1 != ' ')
        nwords++;
return nwords;
}

我希望这会起作用

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