题目
编写一个程序,输入一个字符串(长度不超过80),然后统计出该字符串当中包含有多少个单词。例如:字符串“this is a book”当中包含有4个单词。
输入
输入一个字符串(长度不超过80),由若干个单词组成,单词之间用一个空格隔开。
输出
输出一个整数,即单词的个数。
样例输入
this is a book
样例输出
4
解题思路
读入带空格的字符串,每读到一个空格单词个数加一,最后输出单词个数。
易错点
由于字符串带空格,需要使用fgets,而不可使用scanf。
代码
#include<stdio.h>
#include<string.h>
int main()
{
char str[81];//长度小于80的字符串
fgets(str,81,stdin);
int i,len = strlen(str);
int num_word = 1;//单词数目
for (i=0;i<len;i++)
{
if (str[i]==' ')
num_word++;
}
printf("%d",num_word);
return 0;
}