tags:

views:

80

answers:

3

Is is possible to try to read from a stream but do not change the stream itself (and return bool whether it was a success)?

template <typename T> bool SilentRead (stringstream& s, T& value) {
    stringstream tmp = s;
    tmp >> value;
    return tmp;
}

This doesn't work because stringstream doesn't have public copy constructor. How to do it then?

Is it possible to solve it if we replace stringstream with istream ?

A: 

You're looking for Peek() - http://www.cplusplus.com/reference/iostream/istream/peek/

Richard Berg
peek can lookahead only one char, doesn't it?
Łukasz Lew
+1  A: 

StringStream, refering to this allows you to use tellg and seekg to get / set position. So you could:
1. Get current position
2. Read
3. Set current position to one, that you have just read.

Ravadre
Doesn't work on all streams of course.
MSalters
Of course :). I was refering strictly to std::stringstream (will work for streams on normal files as well).
Ravadre
+2  A: 

In general this is impossible. The underlying streambuf doesn't have an interface. However, you could create a streambuf wrapper. You still wouldn't be able to do non-destructible reads on the stream, but you could do them on your streambuf wrapper.

(A streambuf wrapper is an implementation of the std::streambuf interface which forwards its I/O to an underlying streambuf)

MSalters