Dou*_*oug 0 c++ class input ifstream
简单的问题,希望是一种简单的方法,只是想验证我是否以正确/有效的方式进行操作。
我有一个 T 类对象,通常将其放入在 main() 函数中创建的向量中。它可以是任何类型的数据,字符串,整数,浮点......等。我正在从文件中读取......它是从用户输入并传递给函数的。这是我的基本读入功能:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
insert 只是另一个函数,它将遍历并将数据插入到我的数据结构中。我只是想确保这是传递数据的最佳方式(如果它有效的话)。
您犯了在该条件下测试 eof 的老错误。除非您尝试读取文件末尾,否则不会设置 EOF。所以这个方法会在向量中插入一个你不想要的额外值。
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)
}
}
Run Code Online (Sandbox Code Playgroud)