小程序问题!求最佳答案?!

来源:百度知道 编辑:UC知道 时间:2024/05/29 04:00:46
输入一行字符,统计其中单词的个数。个单词之间用空格分割,空格数可以是多个。(提示:为空格设置标志变量,当输入的字符不是空格而,标志变量为空格的标志时统计)

用C语言!谢谢啦!!!
有没有更好的答案啊!求最佳答案!谢啦!

#include<stdio.h>
void main()
{int i,num=0,word=0;
char string[100];
gets(string);
for(i=0;string[i]!='\0';i++)
if(string[i]==' ') word=0;
else if(word==0)
{
word=1;
num++;
}
printf("There is %d words in this string\n",num);
}

这个应该可以吧,呵呵

谭浩强的c语言教程有写

#include <string.h>
#include <stdio.h>

int main()
{
int n=0;
char *p,s[200];
gets(s);
p=strtok(s," ");
while(p)
{
n++;
p=strtok(NULL," ");
}
printf("have %d words\n",n);
getchar();
return 0;
}