EOF not working as I need

This is a discussion on EOF not working as I need within the C++ Programming forums, part of the General Programming Boards category; forum.cpp contains Code: #include<iostream> #include<fstream> using namespace std; int main(){ ifstream in("forum.txt"); int i; while(!in.eof()) { in>>i; cout <<i <<" ...

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    134

    EOF not working as I need

    forum.cpp contains
    Code:
    #include<iostream>
    #include<fstream>
    using namespace std;
    int main(){
            ifstream in("forum.txt");
            int i;
            while(!in.eof())        {
                    in>>i;
                    cout <<i <<" ";
            }
    }
    forum.txt contains
    Code:
     1 2 3
    When I am running the program forum.cpp
    its printing:
    Code:
    1 2 3 3
    Why and how to solve it?

  2. #2
    Registered User
    Join Date
    Oct 2008
    Posts
    1,262
    eof only returns false after a failed read. So the last read fails, but you never checked for its success. Use something like:
    Code:
    while(in >> i)

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Do not use EOF to control your loops! Instead, put the read/input operation code in the conditional of the loop and test that operation's return result:
    Code:
    while(in >> i) {
        cout <<i <<" ";
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    May 2008
    Posts
    134
    thanks it worked!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 01-18-2008, 03:06 AM
  2. Replies: 4
    Last Post: 01-13-2008, 01:14 AM
  3. EOF isnt working....
    By i_can_do_this in forum C Programming
    Replies: 2
    Last Post: 07-10-2006, 09:58 AM
  4. EOF messing up my input stream?
    By Decrypt in forum C++ Programming
    Replies: 4
    Last Post: 09-30-2005, 03:00 PM
  5. files won't stop being read!!!
    By jverkoey in forum C++ Programming
    Replies: 15
    Last Post: 04-10-2003, 05:28 AM

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