Search code examples
c++istream

Seems redundant use of cin as a condition with if, while


I got a code which seems redundant to me:

    char c;
    cin>>c;
    if(cin&&c=='n')
    //do something

I don't understand the value of introducing cin in if, Isn't it always going to have TRUE value as I've never encountered any case (in my limited experience) where this istream object is not constructed.

Similarly I've seen this as well:

     if(cin)

Please correct me where am I going wrong. Now folks don't post the error-in-stream part as that I already know, the major part is when does a stream fails apart from failure of ios_base::Init


Solution

  • std::cin is an instance of std::basic_istream<char>. Since it's being used in the context of a condition, we are interested it's bool conversion operator. From http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool :

    std::basic_ios::operator bool

    Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail()

    From the documentation, it's clear that if(cin) is meant to check if cin had any errors. More precisely, it's saying "if cin did not encounter an error during it's last operation".

    The condition in if(cin&&c=='n') follows the same principal, but also checks that the input stream supplied n. In other words, "if cin did not encounter an error and returned the character n".