From the book "Accelerated C++":
Ex 4-5-> Write a function that reads words from an input stream and stores them in a vector. Use that function both to write programs that count the number of words in the input, and to count how many times each word occurred.
This is the code I am trying to run:
#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;
}
Now, when I try to run the code, it gets stuck at the input and keeps reading until I abort the program using Ctrl+C. What is wrong with my code?