0

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

tadman
  • 208,517
  • 23
  • 234
  • 262
Gaurav
  • 201
  • 1
  • 11
  • 1
    http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool – Mooing Duck Jul 19 '17 at 18:26
  • @MooingDuck So when can a stream encounter some error: can you give me some examples, links? – Gaurav Jul 19 '17 at 18:29
  • 1
    Gurav `int x, cin >> x;` with user input "FUBAR!", which cannot be converted to an `int`. It's a bit harder with a `char`. – user4581301 Jul 19 '17 at 18:36
  • @user4581301 An what if there is nothing to input, just plain cin -> I've edited the question please have a look. – Gaurav Jul 19 '17 at 18:40
  • 2
    @Gaurav `cin` is not in an error state "when it's not constructed". It's in a bad state when it encounters errors while extracting data. An example of how it could fail in your snippet is if it encounters an end of file, such as if your program's input is being piped from a file or from another program that's ended. – François Andrieux Jul 19 '17 at 18:41

1 Answers1

4

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".

Community
  • 1
  • 1
François Andrieux
  • 28,148
  • 6
  • 56
  • 87