DeNice
DeNice

Reputation: 117

Cin, cin.get and a thing that I cant understand

Is this right that I can write a cycle like this

char temp;
while(cin.get(temp)) {
...
}

And it will stop when there are no symbols in input stream and wont execute if stream is empty? Well, I know its not true, bc when I try - it works same as cin >> temp. Then, how am I supposed to know that the stream is empty and this cycle have to stop?

Upvotes: 0

Views: 44

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409186

The overload of get that you use returns a reference to the stream object.

Stream classes have a boolean conversion operator which returns false on error or end of file.

So if you press the end of file key-sequence (Ctrl-D on POSIX systems like Linux or macOS, or Ctrl-Z on a new line on Windows) then that will propagate up to the stream and the loop-condition will become false and the loop end.

If you want to end the loop on a specific character, say newline, then you need to add it in the condition:

while (cin.get(temp) && temp != '\n')

Upvotes: 5

Related Questions