views:

613

answers:

3

Simple question, hopefully an easy way and just want to verify I'm doing it the correct / efficient way.

I have a class T object, which is typically put into a vector that is created in my main() function. It can be any kind of data, string, int, float.. etc. I'm reading from a file... which is inputted from the user and passed onto the function. Here is my basic read in function:

template <class T, class U>
void get_list(vector<T>& v, const char *inputFile, U)
{
ifstream myFile;
T object;

myFile.open("inputFile")
while(!myFile.eof())
   {
   myFile >> object;
   insert(v, object, U)
   }
}

insert is just another function that will go through and insert the data into my data structure. I just want to make sure this is the best way to pass that data on if it will even work.

+1  A: 

It looks like it will work fine, and I would say this is probably the best way to do it. But why are you asking here instead of just testing it yourself?

SoapBox
I'm not looking for someone to write code, I'm just attempting to find a good method of taking input from a file and inserting it into an object class as I have never done that before. No I'm not sitting in class writing this stuff down for a grade. I just don't want to write it all only to
Doug
Have obscure error messages I don't understand because my basic input function doesn't work correctly because I lack the knowledge for that method of grabbing data from files.
Doug
+1  A: 

Don't use .eof() on a stream in a while-condition. The condition will evaluate to true only after an attempt to read past the end of the file has been made. a better way is to do

while(myFile >> object)
    insert(v, object, U);

Your use of U is flawed. I have no idea what it is used for. One time it is used as a type, but then another time you pass it to the insert function as a value.

Johannes Schaub - litb
+4  A: 

You made the old mistake of testing against eof in the condition. EOF is not set until you try and read past the end of file. So this method will insert one extra value into the vector that you don't want.

template <class T, class U>
void get_list(vector<T>& v, const char *inputFile, U)
{
    ifstream myFile("inputFile");  // Why hard code this?
                                   // When you pass inputFile as a parameter? 
    T object;


    while(myFile >> object)  // Get the object here.
                             // If it fails because of eof() or other
                             // It will not get inserted.
    {
         insert(v, object, U)
    }
}
Martin York