C ++ Opening a file and entering data into a class object
Simple question, hopefully an easy way and just want to confirm that I am doing this correctly / efficiently.
I have an object of class T, which is usually put into a vector that is created in my main () function. It can be any data, string, int, float, etc. I am reading from a file ... which is entered by the user and passed to a function. Here is my main reading 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 another function that will go through and insert data into my data structure. I just want to make sure that this is the best way to pass this data, if it even works.
source to share
You made the old eof testing error in state. EOF is not set until you try and read the end of the file. So this method will add one extra value to the vector that you don't need.
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)
}
}
source to share
Do not use .eof()
for a stream in while
-condition. The condition will be evaluated as true only after an attempt has been made to read past the end of the file. the best way to do
while(myFile >> object)
insert(v, object, U);
Usage is U
spoiled. I have no idea what it is used for. It is used once as a type, but then at other times you pass it to a function insert
as a value.
source to share