我需要一个函数来打开文件并填充我的向量。我想过在没有参数的向量函数(所以我会写 list = fileBeg())和有向量参数的 void 函数(所以我会直接传递我的 list:fileBeg(list))之间选择。我选择了第二种方式,因为我也需要我的ifstream对象是全局的,这样我就可以写下我的输出,这样我的函数就会像fileBeg(list, file)一样工作,但我不知道该怎么做。目前我有。
void fileBeg(std::vector <student> * list, std::ifstream * file) {
std::string fileName;
std::cout << "Input name of file: ";
std::cin >> fileName;
std::ifstream (* file)(fileName);
student temp;
while(* file >> temp){
(* list).push_back(temp);
}
}
但很明显,我得到的错误是 std::ifstream (* file)(fileName);
因为这是对ifstream对象文件的重新定义。我需要类似(* file)(fileName)这样的东西,就像我们写i = 5一样,如果i已经初始化了,但是这样做不行。
我可以用全局变量来做,即使对于当前任务来说是可以的,但我认为这不是一个好习惯。
流是不可赋值的,所以你的方法即使用正确的语法也不能工作。
但是文件流有一个 open
这样 file->open(fileName);
是你要找的东西。
当然,你应该随时检查你是否成功打开一个文件。
file->open(fileName);
if (file->is_open())
{
student temp;
while (*file >> temp){
list->push_back(temp);
}
else
{
std::cout << "failed to open file!!\n";
}