Reputation: 537
I am trying to use the stream iterators to read and output words from the console. Here is my attempt:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
vector<string> stringVec;
copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(stringVec));
sort(stringVec.begin(), stringVec.end());
unique_copy(stringVec.cbegin(), stringVec.cend(), ostream_iterator<string> (cout, "\n"));
return 0;
}
When I input "this is it" and press Return in the console, the cursor there keeps on blinking (indicating that it's waiting for input).
Can anyone please offer some insights on my approach?
Thanks in advance.
Upvotes: 3
Views: 2975
Reputation: 56479
In your case, you can use getline
and istringstream
. It reads a string until \n
and then passes it to copy.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
...
vector<string> stringVec;
string str;
getline(cin, str);
istringstream ss(str);
copy(istream_iterator<string>(ss),
istream_iterator<string>(),
back_inserter(stringVec));
sort(stringVec.begin(), stringVec.end());
unique_copy(stringVec.cbegin(),
stringVec.cend(),
ostream_iterator<string> (cout, "\n"));
Two same questions in a day, you can read this.
Upvotes: 1
Reputation: 47784
You need to provide a EOF for istream_iterator<string>()
, which constructs the end-of-stream iterator.
Use Ctrl+Z or F6 or (Ctrl+D on linux ) to stop getting input from stream
Upvotes: 2