Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stream iterators

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.

like image 479
Roy Avatar asked Mar 18 '26 03:03

Roy


2 Answers

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

like image 158
P0W Avatar answered Mar 19 '26 16:03

P0W


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.

like image 36
masoud Avatar answered Mar 19 '26 17:03

masoud