0

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ravi Soni
  • 141
  • 1
  • 12
  • Possible duplicate of [How to cin to a vector](https://stackoverflow.com/questions/8377660/how-to-cin-to-a-vector) – Stack Danny Jun 29 '17 at 19:46
  • 4
    Use Ctrl-Z or Ctrl-D to signal end-of-file. –  Jun 29 '17 at 19:48
  • Do you want to read from the terminal (stdin) or from a file? If you want to do the former, Neil's answer will do the trick. If you want to do the latter, you can use a [std::ifstream](http://www.cplusplus.com/reference/fstream/ifstream/) initialized with the file name instead of cin. – Tobias Ribizel Jun 29 '17 at 19:57
  • Thank you @NeilButterworth . Ctrl-D did the job. – Ravi Soni Jun 29 '17 at 20:19
  • @StackDanny Thank you for your reference. I found about sstream and will come back to it once I learn about it – Ravi Soni Jun 29 '17 at 20:21

0 Answers0