从“Accelerated C ++”一书中可以看出:
Ex 4-5->编写一个从输入流中读取单词并将其存储在向量中的函数。使用该函数既可以编写计算输入中字数的程序,也可以计算每个单词出现的次数。
这是我试图运行的代码:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using std::cin; using std::cout;
using std::vector; using std::sort;
using std::endl; using std::string;
using std::istream;
istream& read_words(istream& in, vector<string>& words) {
if (in) {
words.clear();
string word;
while (in >> word)
words.push_back(word);
in.clear();
}
return in;
}
int main() {
vector<string> words;
read_words(cin, words);
cout << "Num of words: " << words.size() << endl;
sort(words.begin(), words.end());
string prev_word = "";
int count = 0;
for (vector<string>::size_type i = 0; i < words.size(); ++i) {
if (words[i] != prev_word) {
if (prev_word != "")
cout << prev_word << " appeared " << count << " times" << endl;
prev_word = words[i];
count = 1;
}
else
++count;
}
cout << prev_word << " appeared " << count << " times" << endl;
return 0;
}
现在,当我尝试运行代码时,它会卡在输入端并继续读取 直到我使用 Ctrl + C 中止程序。我的代码出了什么问题?