Description
输入一行字符(少于300个字符),以回车结束,统计其中单词的个数。各单词之间用空格分隔,空格数可以是多个。
Input
输入一字符串,以回车结束。
Output
输出该字符串中单词的个数
Sample Input
This is a c program.
Sample Output
5
#include<cstdio>
#include<cstdlib>
#include<cstring>
int main()
{
char ch;
int _count = 0;
int word = 0;
while((ch = getchar()) != '\n')//出现TLE的原因:数据里面没有出现换行符就结束了
{
if(ch == EOF)//加这行之前 出现TLE
break;
else
{
if(ch == ' ')
word = 0;
else if(word == 0)
{
word = 1;
_count++;
}
}
}
printf("%d\n" , _count);
return 0;
}
#include<cstdio>
#include<cstdlib>
#include<cstring>
char str[305];
int main()
{
while(gets(str) != NULL)
{
int _count = 0;
int word = 0;
for(int i = 0 ; str[i] != '\0' ; i++)
{
if(str[i] == ' ')
word = 0;
else if(word == 0)
{
_count++;
word = 1;
}
}
printf("%d\n" , _count);
}
return 0;
}