本题目要求编写程序统计一行字符中单词的个数。所谓“单词”是指连续不含空格的字符串,各单词之间用空格分隔,空格数可以是多个。
输入格式:
输入给出一行字符。
输出格式:
在一行中输出单词个数。
输入样例:
Let's go to room 209.
输出样例:
5
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
char s[10010];
int main()
{
gets(s); //第二个参数表示最大读取字符数量
int len = strlen(s); //第三个参数指明要读入的文件。如果读入从键盘输入的数据,以stdin(标准输入)作为参数。
int cnt = 0;
for (int i = 0; i < len; i++)
{
if ((s[i] != ' ' && s[i + 1] == ' ') || (s[i] != ' ' && s[i + 1] == '\0')) //注意末尾多了一个'\n'。
cnt++;
}
printf("%d\n", cnt);
return 0;
}