Zebrafish
Zebrafish

Reputation: 13886

What is it about std::cin that makes the program halt?

My understanding is that std::cin is a std::istream object. std::ostream and std::istream objects hold a buffer of characters, or at least refer to them. When doing std::cin >> myvar; my understanding is you're using the >> extraction operator on the std::istream object to extract from the stream buffer. But I don't understand what it is about this that makes the program stop. I've been testing it and I've noticed that it only halts the program if it's empty it seems, because doing:

char c;
std::cin >> c;  // Awaits input from the console
// I input: 1, 2, 3
std::cin >> c;  // Extracts the 2, no halt
std::cin >> c;  // Extracts the 3, no halt

std::cin >> c; // Awaits input from the console

Basically I wanted to know is this behaviour part of the std::istream object. That when it's empty it halts until something is put in it ? I tried to test this by creating my own std::istream object, but it wouldn't compile, an error saying something about protected.

Upvotes: 0

Views: 152

Answers (1)

Pete Becker
Pete Becker

Reputation: 76245

Don't get hung up on "the buffer". All input (well, usually) is buffered. That's a convenience, because reading a character at a time from hardware can be really slow; reading a bunch of characters at once and storing them somewhere (the buffer) can be much faster. That doesn't affect what's underneath. When you read a character, if there's nothing in the buffer, the system looks to the hardware for the next character. If it finds a character, it gives that back to you, and maybe it reads more characters and stores them in the buffer; the read function doesn't return until it's read the next character and done any appropriate buffering, or discovered that it's at the end of the input stream.

When you reach the end of an input stream, trying to read gives you EOF. When the input stream is text from a file, that's easy to detect: when you reach the end of the file, you're at the end of the input stream. When the input stream is the console, it's easy to get confused. The console doesn't have an inherent end: you might just be taking a coffee break and expecting to type more stuff when you come back. So unless you've told the system that the console is at the end of its input, it will just wait for more. The way you tell the console that it's at the end of its input depends on the system; on UNIX systems you do it by typing ctrl-D; under Windows it's ctrl-Z.

Upvotes: 1

Related Questions