reading data from a file

This is a discussion on reading data from a file within the C++ Programming forums, part of the General Programming Boards category; I am trying to read data from a file and put that data into a link list. My problem is ...

  1. #1
    Registered User brianptodd's Avatar
    Join Date
    Oct 2002
    Posts
    66

    reading data from a file

    I am trying to read data from a file and put that data into a link list. My problem is that even if the file is empty, my function still adds junk to my link list.

    Here is the function to read from the file and add, if there is data there:

    Code:
    template <class Type>
    void linklist<Type>::readFile (char * filename)
    {
    	ifstream input_data;
    	input_data.open(filename);
    
    	if (!input_data)
    		cout << "File could not be opened." << endl;
    
    	Type chore;
    	while (!input_data.eof())
    	{
    
    			getline(input_data, chore);
    			node<Type> *new_node = new node<Type>(chore);
    
    			add(new_node);
    			delete new_node;
    			chore.erase(chore.length());
    	}
    
    	input_data.close();
    }
    Any ideas why it reads junk in from an empty file?

    Thanks

    Brian
    "In theory, there is no difference between theory and practice. But, in practice, there is."
    - Jan L.A. van de Snepscheut

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,765
    > Any ideas why it reads junk in from an empty file?
    For the reasons listed in the FAQ

    eof() is only true AFTER a read has failed, so you always end up executing the loop at least once (reading nothing into your uninitialised variables).

    Try
    Code:
    while ( getline(input_data, chore) ) {
        // do stuff
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 04:44 PM
  4. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 05:10 PM
  5. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM

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