if (cin >> a) {

This is a discussion on if (cin >> a) { within the C++ Programming forums, part of the General Programming Boards category; how do cin works ? Code: if (cin >> a) { ............ } else {......................... } assume that a is ...

  1. #1
    Registered User
    Join Date
    Nov 2007
    Posts
    164

    if (cin >> a) {

    how do cin works ?

    Code:
    if (cin >> a) {
    
    ............
    
    }
    else {.........................
    }
    assume that a is int, if the the correct data is intered i.e. a 5 it becomes true, how ?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    The operator >> overload for streams return a reference to the same stream. The stream itself can be evaluated in a boolean condition to true or false through a conversion operator.

    What happens is something like:
    1) try to read input into int a
    2) if it fails, cin is switched into a failed state
    3) return cin after the operation
    4) convert cin into something that can be evaluated in a boolean context. Probably cin is converted to void*: if it is in good state, the conversion returns the pointer to cin, else it returns NULL.
    5) pointers can be evaluated: NULL is false, anything else is true.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. cin >> string // multiple lines
    By msshapira in forum C++ Programming
    Replies: 7
    Last Post: 05-27-2009, 04:39 AM
  2. cin >>
    By TehClutchKiller in forum C++ Programming
    Replies: 4
    Last Post: 06-06-2008, 02:28 AM
  3. cin >> something
    By junkeat90 in forum C++ Programming
    Replies: 2
    Last Post: 01-11-2008, 04:45 AM
  4. cin >> buf endless loop
    By cfriend in forum C++ Programming
    Replies: 2
    Last Post: 10-07-2005, 04:01 PM
  5. cin >> char[]
    By Luigi in forum C++ Programming
    Replies: 3
    Last Post: 04-04-2003, 12:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21