gpt4 book ai didi

C++ 打开文件并向类对象输入数据

转载 作者:太空宇宙 更新时间:2023-11-04 15:55:12 24 4
gpt4 key购买 nike

简单的问题,希望是一种简单的方法,只是想验证我是否以正确/有效的方式进行操作。

我有一个 T 类对象,它通常被放入一个在我的 main() 函数中创建的 vector 中。它可以是任何类型的数据、字符串、整数、 float 等。我正在从一个文件中读取...这是从用户输入并传递给函数的。这是我的基本读入函数:

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 只是另一个函数,它将通过并将数据插入到我的数据结构中。我只是想确保这是传递该数据的最佳方式,如果它能正常工作的话。

最佳答案

您犯了在条件中针对 eof 进行测试的老错误。在您尝试读取文件末尾之前,不会设置 EOF。因此,此方法会将一个额外的值插入到您不需要的 vector 中。

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

关于C++ 打开文件并向类对象输入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/282570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com