Malachi
Malachi

Reputation: 2463

C++ istream::peek - shouldn't it be nonblocking?

It seems well accepted that the istream::peek operation is blocking.

The standard, though arguably a bit ambiguous, leans towards nonblocking behavior. peek calls sgetc in turn, whose behavior is:

"The character at the current position of the controlled input sequence, as a value of type int. If there are no more characters to read from the controlled input sequence, the function returns the end-of-file value (EOF)."

It doesn't say "If there are no more characters.......wait until there are"

Am I missing something here? Or are the peek implementations we use just kinda wrong?

Upvotes: 2

Views: 960

Answers (3)

Pete Becker
Pete Becker

Reputation: 76458

When I get confused about console input I remind myself that console input can be redirected to come from a file, so the behavior of the keyboard more or less mimics the behavior of a file. When you try to read a character from file, you can get one of two results: you get a character, or you get EOF because you've reached the end of the file -- there are no more characters to be read. Same thing for keyboard input: either you get a character, or you get EOF because you've reached the end of the file. With a file, there is no notion of waiting for more characters: either a file has unread characters or it doesn't. Same thing for the keyboard. So if you have't reached EOF on the keyboard, reading a character returns the next character. You reach EOF on the keyboard by typing whatever character your system recognizes as EOF; on Unix systems that's ctrl-D, on Windows (if I remember correctly) that's ctrl-C. If you haven't reached EOF, there are more characters to be read.

Upvotes: 2

M.M
M.M

Reputation: 141648

The description from cppreference.com might be clearer than the one in your question:

Ensures that at least one character is available in the input area by [...] reading more data in from the input sequence (if applicable)."

"if applicable" does apply in this case; and "reading data from the input sequence" entails waiting for more data if there is none and the stream is not in an EOF or other error state.

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490623

The controlled input sequence is the file (or whatever) from which you're reading. So if you're at end of file, it returns EOF. Otherwise it returns the next character from the file.

I see nothing here that's ambiguous at all--if it needs a character that hasn't been read from the file, then it needs to read it (and wait till it's read, and return it).

If you're reading from something like a socket, then it's going to wait until data arrives (or the network stack detects EOF, such as the peer disconnecting).

Upvotes: 4

Related Questions