0

Hi everybody. I hope nobody is working too hard.

I am trying to figure out a way to use the peek() method of the stringstream class but looking
more than one place forward.

For example, if I use stringstream.peek() it will let me know the value one value ahead of the current cursor position. Can I check 2 or 3 positions ahead of the cursur without actually moving the cursure such as when you use seekg()?

Thanks

2
Contributors
2
Replies
18
Views
2 Years
Discussion Span
Last Post by christinetom
1

The reason for the limited amount of "peeking" is because certain types of streams cannot accomodate more than a single character peeking (and no seeking). But for the streams that can easily support moving back-and-forth (seeking) in the underlying data, there is no reason to use peek() instead of the tellg / seekg method. For instance, file-streams can accomodate seeking around the data, although it's preferrable to read/write sequentially or seek as little as possible. In the case of string-streams, they support seeking around the data with ease, and there is essentially no significant cost to seeking back-and-forth anywhere in the data.

So, don't use "peek", use the tellg/seekg method, as so, for example:

std::string peek_next_word(std::istream& in) {
  std::string result;
  std::streampos p_orig = in.tellg();
  in >> result;
  in.seekg(p_orig);
  return result;
};

Basically, any kind of implementation of a multi-character peeking function would have to use a mechanism similar to the above code (tellg / read / seekg) and that's why there is no reason to have a separate function (e.g., "peek_n(str,n);") in the standard streams to do this, because it's not gonna be more efficient than this tellg-seekg method.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.