Thread: Read from a file

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    14

    Read from a file

    Hello everyone:
    I am trying to write a while loop to control reading from a file to an array. The array can only hold ten integers. The file may contain any number of integers with one per line. I need a loop test condition that will read from the file until either the end of the file is reached or the array is full. Here is what I have so far:

    Code:
    cin >> temp;
    arrayIndex = 0;
    while ( array index < arraySize ||                           )
    
    {
    array[arrayIndex] = temp;
    arrayIndex++;
    cin >> temp;
    }
    Can someone help me please?

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    You can just use the stream cin itself like a boolean expression to determine whether it has reached the end or encountered an error. And any input operation returns the stream, so (cin >> temp) refers to the stream.

    So the canonical form of reading integers until the end of stream or error would be
    Code:
    while (cin >> temp) {
      // do something with temp here
    }
    That should put you on the right track.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 12-07-2012, 10:44 PM
  2. Replies: 12
    Last Post: 06-18-2012, 08:23 AM
  3. Open a file, read it ... and ... read it again
    By Tiago in forum C Programming
    Replies: 1
    Last Post: 04-17-2010, 03:32 AM
  4. How can I know the actual bytes read in a file read
    By pliang in forum C++ Programming
    Replies: 1
    Last Post: 06-08-2005, 04:23 PM