Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have written a simple code:

#include <iostream>
using namespace std;
int main()
{
  int a, b;
  while (cin >> a >> b)     //Note the cin inside while loop
  { 
    cout << a << b << "
";
  }
}

We know that while loop functions only when the expression evaluates true (1) or false(0). How come cin is evaluating true and false.

Also how is while loop running when I am entering a number and stops when I enter something non-digit? How is it evaluating true and false?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
353 views
Welcome To Ask or Share your Answers For Others

1 Answer

When you writes cin >> a, you are actually using the std::istream::operator>>, according to the reference here, this operator returns an istream& object reference, and took the right hand variable (reference) as its argument. This is how you can chain it like: cin >> a >> b.

To see this cin >> a >> b chain another way, when break down, it is this two steps:

  • First step, cin >> a returns some intermediate value, let's say it is x. (You can actually try auto x = cin >> a.
  • Second step, you are doing (cin >> a) >> b, when we use this intermediate value x, we could write it as x >> b.

So what the hell is this x? x here stays a same position as the cin, it is an object of istream& type.

Therefore, when you talk about true or false, you are actually talking about whether this returned istream& reference, refer to an object, whether it is true or false. It would be false when the standard output catch an EOF sign (like when you type Ctrl-C in unix like system, or when you have read to the end of a file).

Your code, therefore, could be expanded as

#include <iostream>
using namespace std;
int main()
{
  int a, b;
  auto x = cin >> a >> b
  while (x)
  { 
    cout << a << b << "
";
  }
}

If you are using an IDE like Visual Studio, you could point your mouse at the variable x, it would prompt you x's type, and that would be an istream&.

Also, thanks to Bob__, this istream& class could be convert to an ios::operator bool class, as is written here, whether it is true or false represents the state(ios_base::iostate) of this stream, it therfore,

makes it possible to use streams and functions that return references to streams as loop conditions, resulting in the idiomatic C++ input loops such as while(stream >> value) {...} or while(getline(stream, string)){...}. Such loops execute the loop's body only if the input operation succeeded.

To further your understanding, you should read the operator (overloading) chapter in your textbook.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...