I need to try to peek multiple characters from a std::istream
(which could be std::cin
), so I wrote a simple loop to call get()
lots of times and then putback()
lots of times:
std::vector<char> peek_many(std::istream& is, int N) {
std::vector<char> data;
data.reserve(N);
for (int i = 0; i < N; ++i) {
data.push_back(is.get());
}
for (int i = 0; i < N; ++i) {
is.putback(data[N-i-1]);
}
return data;
}
Is this guaranteed to work on all istream
s (whether I'm reading a file, cin
, istringstream
, etc)? If not, why not?