What is cin doing inside argument of if? [duplicate]
Possible Duplicate:
How would st开发者_开发百科d::ostringstream convert to bool?
#include<iostream.h>
void main() {
if(cin>>2) { // what is cin>>2 doing inside arg of if
cout<<"if works";
} else {
cout<<"else works";
}
}
We don't get error in this code.But Alwaysif statement works why? how?
cin >> 2 is invalid. cin >> integervar is valid, assuming that's what you mean?
The standard library class ios which basic_istream (and thus cin) inherits from overloads operator void * (and operator!) to allow you to do such tests.
operator void * returns 0 if failbit or badbit is set - aka the last extraction failed.
This is the "standard" way of combining extraction and checking if the extraction succeeded.
if(cin>>2)
This wouldn't even compile. See this : http://ideone.com/MiEkq
What you probably mean is : if(cin>>var)
If that is so, then it means IF the read from the input stream succeeds, then then if block will be executed because after successful read, the returned std::istream & can implicitly convert into true, otherwise it converts into false.
BTW, the return type of main() should be int.
加载中,请稍侯......
精彩评论