Thread: File IO question

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    9

    File IO question

    At the suggestion of some cprogramming experts, I started using filestreams rather than the old style FILE* c code.

    Now I have some problems that I'm having trouble solving. This code opens a file with two columns of double data of unknown length. I want to
    Code:
    ifstream f( filename );
    double a,p;
    
    vector <double> v;
    
    if(f.is_open())
    {
    	while(!f.eof())
    	{
    		f >> a >> p;
    		v.push_back( a );
    		v.push_back( p );
    	}
    }
    else
    	cout << "Unable to open file";
    The problem is that if my input file has a return after the last number, eof says there is still more to read, and the while loop keeps going, pushing 1 additional element onto each vector. Is testing for an identical values the only way to prevent this from happening? Does f >> a >> p raise a flag somewhere that says it didn't read a double?

    Thanks for the help.

    OK, well I seemed to have answered it myself:
    Code:
    if(f >> a)
    This tests for valid input.

    Well I guess I'm still wondering if there would be a way to push the value right onto the vector array without saving it in a temp variable. Something like this:
    Code:
    s.push( f >> double );
    Is this possible?
    Last edited by CaeZaR; 02-06-2006 at 03:25 PM.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    You found the correct solution with if (f >> a), although you can also just move that code to the while control instead of the eof() check.

    You cannot push the variable on to the vector without a temporary because of the way operator>> works. It manipulates an existing object instead of returning a new object.

    If your vector started out filled with values, you could use operator[] or at() to set the data directly without the temporary, but that is not a good solution unless you know exactly how many elements will be in the input file.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > while(!f.eof())
    Read the FAQ as to why using eof to control a loop is bad.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. File I/O Question
    By Achy in forum C Programming
    Replies: 2
    Last Post: 11-18-2005, 12:09 AM
  5. Replies: 3
    Last Post: 03-04-2005, 02:46 PM