#include <iostream> #include <string> #include <sstream> using namespace std; int main() { int count = 0; // 初始化单词数量为0 string line; // 定义字符串变量用于存储输入的每一行 while (getline(cin, line)) { // 使用 getline() 函数逐行读入输入 if (line == "stop") { // 如果输入的是“stop”,则停止循环 break; } stringstream ss(line); // 使用 stringstream 对每一行进行分割 string word; while (ss >> word) { // 使用 >> 运算符将每个单词逐个读入并计数 count++; } } cout << count << endl; // 输出单词数量 return 0; }但这段代码不支持一行有多个单词的情况,请优化
时间: 2024-02-14 12:09:57 浏览: 21
好的,以下是支持一行有多个单词的 C++ 代码实现:
```cpp
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
int count = 0; // 初始化单词数量为0
string line; // 定义字符串变量用于存储输入的每一行
while (getline(cin, line)) { // 使用 getline() 函数逐行读入输入
if (line == "stop") { // 如果输入的是“stop”,则停止循环
break;
}
stringstream ss(line); // 使用 stringstream 对每一行进行分割
string word;
while (ss >> word) { // 使用 >> 运算符将每个单词逐个读入并计数
count++;
}
}
cout << count << endl; // 输出单词数量
return 0;
}
```
这段代码中,我们使用 `getline()` 函数逐行读入输入,并将每一行存储在字符串变量 `line` 中。在每次读入一行后,我们可以使用 `stringstream` 类型对其进行分割,并使用 `>>` 运算符将每个单词逐个读入并计数。这样,无论一行中有多少个单词,都能正确地计算单词数量。最后将单词数量累加到 `count` 变量中,并在循环结束后输出 `count` 即可。