youssef
youssef

Reputation: 623

finishing cin stream after getting values by istream_iterator

I have a simple question concerning iterator , in the following code I used three ways to get values from the pointer of iterator and put them into standard output or into vector , but the cin stream is continuous even after pressing enter key. what should be the bug in this code.... Thanks in advance

#include <iostream>
#include <iterator>
#include <vector>

using namespace std;

int main()
{

    vector<double> My_container ;

    cout << "Enter values separated by spaces : " ;


#define code1

#ifdef code1

    copy (istream_iterator<double>(cin),
          istream_iterator<double>(),
          ostream_iterator<double>(cout)) ;    

#endif // code


/////////////////////////////////////////////////////
#ifdef code2

    istream_iterator<double> eos ;
    istream_iterator<double> basic_input (cin);    

    while (basic_input != eos)
    {
        My_container.push_back(*basic_input) ;
        ++basic_input ;    
    }

    for (int i = 0 ; i < My_container.size() ; i++)
    {
        cout << i << " :" << My_container.at(i) << endl ;
    }

#endif //code2


//////////////////////////////////////////////
#ifdef code3

    istream_iterator<double> stream_end ;
    istream_iterator<double> basic_input (cin);    

    for ( ; basic_input != stream_end; ++basic_input )
    {
        My_container.push_back(*basic_input) ;
    }

    for (int i = 0 ; i < My_container.size() ; i++)
    {
        cout << i << " :" << My_container.at(i) << endl ;
    }

#endif //code3

}

Upvotes: 3

Views: 475

Answers (2)

jrd1
jrd1

Reputation: 10726

Your code isn't wrong per se.

You're getting that behavior simply by design. Why? Because cin skips over whitespace by default.

As @Veritas has noted you have to signal an EOF. To do so:

  • On Windows: Ctrl-D (Actually type that - that's not a keyboard combination)
  • On *nix: Ctrl-D (The actual keyboard combination. Technically, this is actually an EOT)

Why do you have to do this? Since cin skips over whitespace by default, how does it know when to stop reading data? The only way is to signal or input an EOF character (as described above) into the data stream.

Upvotes: 3

Veritas
Veritas

Reputation: 2210

You are waiting for eof in order to close the stream. Pressing enter won't do, it simply puts a newline character in the stream.

You will either have to check for a newline, or signal eof yourself.

Upvotes: 1

Related Questions