VC编程……计算单词个数

来源:百度知道 编辑:UC知道 时间:2024/05/24 12:33:48
有键盘输入一个句子,以回车表示结束,以空格分隔单词,要求输出单词的个数…………
例如:输入 How are you?
输出 3
注意单词之间的空格不仅仅是隔一个,可能很多个,回车之前也可能有…………
看起来很简单,但是我想不出算法来………………
符:
错误的算法一例
#include "stdio.h"
main()
{
char ch;
int i;
while((ch=getchar())!='\n')
{
for(i=1;ch==' ';i++)
scanf("%c",&ch);
}
printf("%d",i);
}

请各位指点一下…………
一楼两个都是错的,麻烦改一下…………
第一个语言没错,可是运算结果错…………
第二个编译错误…………ch2没有赋值之前就用到关系表达式里面了…………
二楼的太多垃圾,要简化,有那么复杂吗…………
真是的,我只想要个好点的算法而已…………

既然你都把回车和空格作为分隔符了,那你怎么停止输入呢?
考虑以回车结束输入,统计单词个数

#include "stdio.h"
int main()
{
char ch, temp = ' ';
int i = 0;
ch = getchar();
while( ch != '\n')
{
if(ch == ' ' && temp != ' ')
i++;
temp = ch;
ch = getchar();
}
if(temp != ' ')
i++;
printf("%d\n",i);
return 0;
}

搜一下应该会有
#include<stdio.h>
int main()
{
int i=0,flag=0,n=0;
char s[50];
printf("please input the sentence\n");
scanf("%[^\n]",&s);/* 接受包括空格字符的字符串*/
printf("the centence contain the words as follow\n");
while(s[i]!='\0')
{
while(s[i]!=32)/*判断是否为空格*/
{
if(s[i]=='\0')/*判断是否结束*/
{
printf("\nThe number of it is %d\n",++n);
return 0;
}
printf("%c