The I/O operator symbol (<and>) returns a value.
This is involved in several questions recently. Let's take a brief note.
First, CIN is an object and does not "return" values, >>and <is the method, with a return value.> The Operation Sequence of the <operator is from left to right, so the following two statements are actually the same:
cin>>a>>b>>c;
(((cin>>a)>>b)>>c);
Operation CIN> A: CallistreamOperator> method to read data and store it in variable. So what is the return value of> or <? The returned value here does not refer to the value in the read variable, but the data that is returned to the left value. Here,> the returned value is Cin, which can be found by tracking the source code:
istream& operator>> (istream& is, char& ch );
istream& operator>> (istream& is, signed char& ch );
istream& operator>> (istream& is, unsigned char& ch );
istream& operator>> (istream& is, char* str );
istream& operator>> (istream& is, signed char* str );
istream& operator>> (istream& is, unsigned char* str )
Of course, you can also test it as follows:
if ((cin >> a) == cin) {
cout << "Equal" << endl; // Yes
} else {
cout << "Not Equal" << endl;
}
Why can we use CIN as a true value criterion?
Cin can be used as follows:
if(cin){}
if(cin>>a>>b){}
while(cin>>a){}
As mentioned above,> the returned value is Cin, and the true value above is equivalent:
if(cin){}
if(cin){}
while(cin){}
If the status of CIN is OK, it is true. If CIN encounters an EOF or an error, false is returned. Why can we use CIN as the true value criterion?
First, let's see how CIN is defined:
extern istream cin;
How can such a value be used as the true value criterion of if? This is because when we use if (CIN) or while (CIN), we actually call an istream method. Write a simple line of code for disassembly and take a look:
int main() {
if(cin){}
return 0;
}
The compilation code is as follows:
In fact, all classes derived from IOs can be forcibly converted to a pointer. If an error flag is set, the pointer is null. Otherwise, the pointer is not null. Test the following code:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ifstream is;
is.open ("test.txt");
if ( (void*)is == 0)// Equal to if(is)
cerr << "Error opening 'test.txt'\n";
return 0;
}