用C语言写:输入一段文字,输出有多少个单词
时间: 2023-08-16 13:07:04 浏览: 40
好的,以下是用C语言实现输入一段文字,输出有多少个单词的代码:
```c
#include <stdio.h>
#include <ctype.h>
int main() {
char text[1000];
int i, count = 0, word = 0;
printf("请输入一段文字:\n");
fgets(text, 1000, stdin);
for (i = 0; text[i] != '\0'; i++) {
if (isalpha(text[i])) {
word = 1;
} else {
if (word == 1) {
count++;
word = 0;
}
}
}
if (word == 1) {
count++;
}
printf("这段文字中有 %d 个单词。\n", count);
return 0;
}
```
以上代码中,我们使用了一个字符串数组 `text` 来存储用户输入的一段文字,使用 `fgets` 函数来获取用户输入。然后我们遍历整个字符串,如果遇到字母,就说明进入了一个单词,将 `word` 的值设为 1。如果遇到非字母字符,就说明一个单词结束了,如果此时 `word` 的值为 1,说明刚才进入了一个单词,将 `count` 的值加 1,并将 `word` 的值设为 0。最后如果 `word` 的值为 1,说明最后一个单词还没有结束,将 `count` 的值再加 1。最后输出单词的数量即可。
希望能对你有所帮助!