C ++ how does While (cin >> x) work?

My question is how,

while(cin>>x) { //code } 

Job. Or, to be more specific, how about this code stops the loop?

From the documentation here , it seems that the → operator returns a &istream . Does this mean that if the reading failed or is at the end of the file, it not only sets eofbit, failbit or badbit, but also returns zero? It doesn’t make sense, so I doubt it.

Is there some kind of implicit eofbit check?

I ask because I hope to implement something similar with 2 classes such as

 class B { //variables and methods } class A { //Variables and methods //Container of B objects. ex. B[] or vector<B> or Map<key,B> &A >> (B b); } int main() { A a; B b; while( a >> b) { //Code } } 

Note. I do not want to inherit from istream , unless there is magic where this work comes from. The reason for this is because I hope to keep as few classes and their dependencies as possible. If I inherit from istream , I will get all my public and protected things, and I am not trying to create an istream object. I just want to copy one REALLY good piece.

Edit: I am using Visual Studio 2010 (which becomes a real pain), and I will need something compatible with it implementation of C ++ 03 + some C ++ 11.

+7
source share
2 answers

Now can you write an example of how I can do this with the above material?

Like this:

 // UNTESTED class B { //variables and methods } class A { bool still_good; //Variables and methods //Container of B objects. ex. B[] or vector<B> or Map<key,B> A& operator>>(B& b) { try_to_fill_b(); if(fail) still_good = false; return *this; } explicit operator bool() { return still_good; } } int main() { A a; B b; while( a >> b) { //Code } } 
+4
source

From the documentation here you can see that the → operator returns & istream. Does this mean that if the reading failed or is at the end of the file, it not only sets eofbit, failbit or badbit, but also returns a null character?

No, a reference is returned to the stream object, but internal flags will be set. Subsequent calls to operator>> will fail after testing these flags.

Is there some kind of implicit eofbit check?

Not sure what the question is. The thread will not try to find whether the next request will fail, but only set the flag if one operation failed because it fell into EOF. Each call to operator>> first checks the state of the stream and will only work if the stream is in good condition.

How does while(cin>>x) ?

There is an implicit conversion from stream to logical. The conversion gives true if the stream is in good condition or false otherwise.

+4
source

All Articles