以下是一个用 C++ 实现统计输入字符串中单词个数的示例代码: ```cpp #include <iostream> #include <string> int countWords(std::string str) { int count = 0; bool inWord = false; for (char c : str) { if (c =='') { if (inWord) { count++; } inWord = false; } else { inWord = true; } } if (inWord) { count++; } return count; } int main() { std::string input; std::cout << "请输入字符串: "; std::getline(std::cin, input); int wordCount = countWords(input); std::cout << "单词个数为: " << wordCount << std::endl; return 0; } ``` 以下是三个改进建议: 1. 可以添加对输入字符串的合法性检查,例如是否为空字符串。 2. 考虑使用更高效的数据结构,如 `std::vector` 来存储单词。 3. 对代码添加更多的注释,以提高代码的可读性。 [2024-12-28 16:20:30 | AI写代码神器 | 278点数解答]