简体   繁体   中英

How to associate file with already initialised ifstream object?

I need a function to open file and fill my vector. I thought between vector function with no arguments (so I would write list = fileBeg()) and void function with vector argument (so I would pass my list straightforward: fileBeg(list)). I chose 2nd way because I also need my ifstream object to be global so that I can write down my output, so that my function will work like fileBeg(list, file), but I'm not sure how to do it. Currently I have:

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

But I obviously get mistake on std::ifstream (* file)(fileName);because it's redefinition of the ifstream object file. I need something like (* file)(fileName), just like we write i = 5 if i is already initialised, but it doesn't work this way.

I could do it with global variable, and even if it's okay for current task, I don't think it's a good habit.

Streams are not assignable so your method cannot work even with the correct syntax.

But file streams have an open method so this file->open(fileName); is what you are looking for.

And of course you should always check if you opened a file successfully or not

file->open(fileName);
if (file->is_open())
{
    student temp;
    while (*file >> temp){
        list->push_back(temp);
}
else
{
     std::cout << "failed to open file!!\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM