Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

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)
    }
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top