I use istream_iterator to read integers from input (until eof) and store them to a vector
after that i want to read a single integer (or maybe a value of another type e.g. string). How can i do that?
the "problematic" code is the following. It does not read the value with cin.
#include<iostream>
#include<iterator>
#include<algorithm>
#include<vector>
using namespace std;
int main(){
// creates two iterators to the begin end end of std input
istream_iterator<int> int_it(cin), eof;
vector<int> int_vec(int_it,eof);
// prints the vector using iterators
cout<<"You gave me the vector: ";
copy(int_vec.begin(),int_vec.end(),ostream_iterator<int>(cout," "));
cout<<endl;
int value;
cout<<"Give me the value you want to search for: ";
cin>>value;
int x=count(int_vec.begin(),int_vec.end(),value);
cout<<"Value "<<value<<" is found "<<x<<" times\n";
}
In a comment, you wrote:
I want to read vector integers until the user press ctrl-D (eof). Then i want to re-user the cin for reading other stuff.
You cannot do that. Once std::cin
/stdin
is closed it cannot be reopened for reading more data from it.
You can use a different strategy though. Instead of relying on EOF to detect the end of input for the vector of integers, you can use something that is not an integer. For example, if your input consists of
1 2 3 4 end
then the reading to int_vec
will stop at the start of the "end" in the input stream. Then, you can use cin.clear()
and cin.ignore()
to clear the error state of the stream and discard the rest of the input in the line before continuing to read more from cin
.
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <limits>
using namespace std;
int main()
{
// creates two iterators to the begin end end of std input
cout << "Input some integers. Enter something else to stop.\n";
istream_iterator<int> int_it(cin), eof;
vector<int> int_vec(int_it, eof);
// prints the vector using iterators
cout<<"You gave me the vector: ";
copy(int_vec.begin(),int_vec.end(), ostream_iterator<int>(cout," "));
cout << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
int value = 0;
cout << "Give me the value you want to search for: ";
cin >> value;
int x = count(int_vec.begin(), int_vec.end(), value);
cout << "Value " << value << " is found " << x << " times\n";
}
Input some integers. Enter something else to stop.
1 2 3 4 end
You gave me the vector: 1 2 3 4
Give me the value you want to search for: 1
Value 1 is found 1 times