c语言 从控制台输入一个句子,统计其中的单词个数。 输入:how are you! 输出:3
时间: 2025-01-15 20:23:19 浏览: 54
在C语言中,你可以使用标准库函数来实现这个功能。首先,你需要读取用户从控制台输入的一行字符串,然后分割成单词。这里可以利用`getchar()`函数逐个字符读入,并用空格作为分隔符判断是否形成新的单词。当遇到非字母数字字符(如空格、标点等),就认为是一个单词结束。
下面是一个简单的示例程序:
```c
#include <stdio.h>
#include <ctype.h> // 包含处理字符类型的功能
int count_words(char *str) {
int word_count = 0;
while (*str != '\0') { // 遍历字符串直到结尾
if (isspace(*str)) { // 如果当前字符是空格
if (word_count > 0) { // 如果之前有单词存在,计数加一
word_count++;
}
} else if (isalpha(*str)) { // 如果当前字符是字母
word_count++; // 单词开始,计数加一
}
str++; // 移动指针到下一个字符
}
// 别忘了检查最后一个单词
if (word_count > 0 && isspace(str[-1])) {
word_count--;
}
return word_count; // 返回单词总数
}
int main() {
char input[100];
printf("请输入一个句子: ");
fgets(input, sizeof(input), stdin); // 从控制台获取一行输入
input[strcspn(input, "\n")] = '\0'; // 去除换行符
int wordCount = count_words(input);
printf("输出:%d\n", wordCount);
return 0;
}
```
当你运行这个程序并输入 "how are you!",它会返回 `3`,表示单词的数量。请注意,此程序假设单词只包含字母和空格,对于其他特殊字符的处理可能会有所不同。另外,如果输入的句子结束符不是空格,需要额外考虑。
阅读全文
相关推荐
















