1

I'm a total newbie to C++, so don't hit me hard :)
I've been trying to grasp how the following piece of code works, but none of the laws of logic seem to apply here.

int a;

while (cin >> a)
    cout << a << "\n";

cout << a << "\n";

What I do is I run the code, enter a value for "a"(let's say a 5), terminate the input stream(I hope that's the right word) with an "|", and the output goes as follows:
5
0
So, I feed the program a value, in the loop this value is still what it should be, but just after the loop it becomes a 0 for no reason I can think of. Thus, I wonder what's going on here.

Whippa
  • 11
  • 2
  • There’s no good reason why the value gets changed, but there’s also not really a compelling reason for the value to remain unchanged: since the last extraction was unsuccessful, reading the value again doesn’t make sense anyway. – Konrad Rudolph Feb 07 '20 at 17:50
  • @Konrad Rudolph thanks, you helped me get the things straight. I didn't know that using a "|" actually caused the extraction to fail and not just terminate it. Also, one of the answers to the first associated question cleared it all up. In short, it's the C++11 (and up) standard that enforces an assignment of a 0 to a variable upon a failed extraction. – Whippa Feb 07 '20 at 18:13
  • To clarify, the extraction “fails” *because* the stream ends. It’s not an actual failure, it’s the iostream way of signalling the end of the stream. If an *actual* failure occurs, `cin.fail()` (and/or `cin.bad()`) is set. However, this is almost certainly not the case for you. There’s a table of the various states at the bottom of this page: https://en.cppreference.com/w/cpp/io/basic_ios/fail – Konrad Rudolph Feb 07 '20 at 18:17
  • "_terminate the input stream(I hope that's the right word) with an "|", and the output goes as follows:_" Technically, "|" doesn't terminate the stream. `cin >> a` invokes the [`operator>>`](https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt) overload that accepts `int`. Since `'|'` is not convertible to an `int` - extraction fails, and, as described in the documentation: Since C++11 "_If extraction fails, zero is written to value and failbit is set._" To end the stream gracefully, consider writing EOF character instead. – Algirdas Preidžius Feb 07 '20 at 19:14

0 Answers0