Thread: What does cin.eof() do?

  1. #1

    What does cin.eof() do?

    What I always see is !cin.eof() in certain loop. Does it test for end of file? How to define "end of file" by myself?

  2. #2
    It does test for the end of the file, dunno how you would do it on your own though.

    More commonly used like this:

    ifstream fileIn( "test.txt" );
    while( !fileIn.eof() )
         fileIn >> stuff;
         fileIn >> morestuff;

  3. #3
    Here's how I understand it, at least for file handling. I can't say that I have seen eof() used with cin however. In any event, when using files, the OS places an EOF symbol (I forget the ASCII equivalent of EOF) in file when file is created. The OS automatically keeps placing the EOF symbol at the end of file input with each new file input. When the file is read, the EOF symbol is then read as any other symbol by the stream. Let's say the file contains:

    1 2 3 EOF

    and you read file with fin >> after appropriately declaring and initialize stream and you are storing the values in the file in an int array at index i:

    ifstream fin(filename);
    int array[4];
    int i = 0;

    while(!fin.eof()) //means as long as you don't find the end of file
    //read data into correct position
    fin >> array[i++];

    fin.eof() will look at each input and compare it against EOF. If the input is not EOF it will return 0, making !fin.eof() non zero (or true) and loop body can proceed. If EOF is found, then positve value is returned, !fin.eof() is 0 (or false) and loop body will stop.

    This probably isn't completely correct either, but it should be reasonably close.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. cin.eof()
    By Loic in forum C++ Programming
    Replies: 2
    Last Post: 05-13-2007, 07:52 PM
  2. MS VC++ cin.eof ignoring first ^Z. What up?
    By dstocks in forum C++ Programming
    Replies: 1
    Last Post: 01-12-2002, 05:16 PM