My question is how does,
while(cin>>x)
{
//code
}
work. Or to be more specific, what about that code halts the loop?
From the documentation here, it looks like the >> operator returns a &istream
. Does that mean if the read fails or hits the end of file it not only sets the eofbit, failbit or badbit but also returns a null? That doesn't really make sense so I doubt that's it.
Is there some kind of implicit check of the eofbit?
I ask because I'm hoping to implement something similar with 2 classes like this,
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'm not looking to inherit from istream
unless it's where the magic that makes this work come from. The reason for this is I'm hoping to keep the classes and their dependencies as small as possible. If I inherit from istream
I will receive all its public and protected stuff and I'm not trying to create an istream
like object. I just want to copy one REALLY nice piece of it.
Edit: I'm using Visual Studio 2010, (which is becoming a real pain) and I'm going to need something compatible with it's implementation of C++03 + some C++11.
Now could you write up an example of how I can do that with the above stuff?
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
}
}