Thread: How do I know if I am at the end of a file (and other FILEIO Qs?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    System.out.println("");
    Join Date
    Jan 2005
    Posts
    84

    How do I know if I am at the end of a file (and other FILEIO Qs?

    I am trying one of the challenges offered on the website for counting the number of lines in a file. How can I tell when I am through reading a file? Basically I don't really know how so I ran a little test. I created a text file with lines (numbers) in it and read 5 lines and printed out what was read after each step. Well, what I discovered was that if it doesn't read anything the value never changes. This isn't very helpful as checking if it's the same before and after reading each line doesn't necessarily tell you if you are done because if two lines are the same then the result would be the same even though you aren't at the end of the line. Anyway, that was my thought process and here's my code.
    Thanks in advance.

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int test;
    int main()
    {
       ifstream in ("input.txt");
       //read the line and then print it out so I can see what's 
       //been read.
       in>>test;
       cout<<test; 
       in>>test;
       cout<<test;           
       in>>test;
       cout<<test;           
       in>>test;
       cout<<test;           
       in>>test;
       cout<<test;           
       
       cin>>test; //simply so the window stays open
    }
    And input.txt contains:

    Code:
    1
    5
    3
    The output I got was this:

    Code:
    15333
    Also if I wanted to prompt the user for the filename shouldn't I be able to simply do a cin>>someString and then where I have "input.txt" above when defining my ifstream object just put someString in place of "input.txt"? I kept getting errors when doing this.
    Last edited by Loctan; 03-07-2005 at 02:15 AM.

Popular pages Recent additions subscribe to a feed