cin question.

From: R. Clayton <rvclayton_at_acm.org>
Date: Mon, 5 Feb 2007 19:45:34 -0500

I am using the following code block to retrieve numbers:

---------------------------
cin >> number;
while(cin)
 {
 number_holder.push_back(number); //I know we can't use vectors for class
 cin >> number;
 }
---------------------------

This loop stops if something other than a number is input, but shouldn't
it also stop when there are no more numbers in the stream (i.e. when cin
is false)?

  Ah, tricky question. Before I answer it, though, I'd like to
  congratulate you on correctly checking for end-of-file: first
  read the stream, then check for eof. It drives me up the wall when
  I see code like this:

    // this is bad code.

    while cin.eof()
      cin >> x
      // whatever.

  This makes an extra loop with the last value of x; I used to enjoy
  writing tests that exploited that error to make programs fail.

  On to your question. Your code does everything but check for
  end-of-file. The full answer is long and complicated; you can
  find the details at

    http://www.cplusplus.com/reference/iostream/ios/operator_voidpt.html

  The short answer is that, when taken as a boolean value, an input
  stream is false when there's a failure or an error, but not when
  there's an end-of-file (I have no idea why it works this way, and I
  probably don't want to know). If you want to test for eof, you
  have to do it explicitly using the eof() stream predicate.

  But using eof() tests only for eof, not for failures or errors.
  You probably want to test for all three; the easiest way to do that
  is use the good() stream predicate:

    cin >> x
    while cin.good()
      // blah blah blah

  good() returns true only when there are no errors of any kind.

  You might be wondering why

    while (cin >> x)

  works as expected; if so, you're probably expecting the wrong
  thing. The eof bit gets set when cin bangs into the eof, but I've
  said above the eof bit doesn't matter when cin gets turned into a
  boolean (the value of the cin >> x expression is cin). What really
  happens is that the read into x fails on eof (there's nothing to
  read into x); this sets the fail bit. When cin gets turned into a
  boolean, it's the fail bit causes cin to be false, not the eof bit.
Received on Mon Feb 05 2007 - 19:46:36 EST

This archive was generated by hypermail 2.2.0 : Sun Feb 11 2007 - 19:10:41 EST