-1

I know while(cin) means while all previous operations on cin have succeeded, continue to loop. But what does that really mean?

Does it mean "after I have inputed all the values I want continue the loop" or "after completing the inputes that comes before continue the loop" or what? I'm confused.

If there is no imput before while(cin) what then will happen?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Lekan
  • 115
  • 1
  • 6
  • 2
    Possible duplicate of [What's the difference between while(cin) and while(cin >> num)](https://stackoverflow.com/questions/19483126/whats-the-difference-between-whilecin-and-whilecin-num) – lurker Oct 26 '19 at 13:20
  • It really means that `cin` is currently in a good state. Inside the loop, still need to check for successful streaming into a variable, `if (!(cin >> num)) throw "Nope";` (or however one wants to handle failure). – Eljay Oct 26 '19 at 13:22
  • Initially `cin` will be in good state, so it's `true`. – rustyx Oct 26 '19 at 13:37

2 Answers2

2

The class std::istream inherits the class std::basic_ios that contains the conversion operator

explicit operator bool() const;

that returns !fail().

In the context of the while statement the object of the type std::cin is converted to an object of the type bool using this operator.

In fact this while loop is equivalent to

while ( not std::cin.fail() )

That is the loop will perform its iterations until some error or end of the stream will be encountered.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

With a simple piece of code, you can get your code to run over and over (something like a infinite loop):

#include <iostream>
using namespace std;

int main() {
   while (cin) {
      cout << "HI";
   }
}
Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
Farbod Ahmadian
  • 728
  • 6
  • 18
  • Yeah, but there are no former inputs. What if there are other inputs outside the while statement – Lekan Oct 26 '19 at 13:34