以下是一个用 C 语言解决此问题的示例代码: ```c #include <stdio.h> #include <ctype.h> int countWords(char str[]) { int count = 0; int inWord = 0; for (int i = 0; str[i]!= '\0'; i++) { if (isalpha(str[i])) { if (!inWord) { count++; inWord = 1; } } else { inWord = 0; } } return count; } int main() { char str[1000]; printf("请输入一行字符: "); fgets(str, sizeof(str), stdin); int wordCount = countWords(str); printf("单词数量: %d\n", wordCount); return 0; } ``` 在上述代码中,`countWords` 函数用于统计单词的数量。通过遍历输入的字符串,当遇到字母且当前不在单词中时,单词数量加 1,并标记处于单词中。遇到非字母字符时,标记为不在单词中。在 `main` 函数中,获取用户输入的字符串,并调用 `countWords` 函数计算并输出单词数量。 [2024-11-10 22:00:28 | AI写代码神器 | 289点数解答]