gpt4 book ai didi

c++ - 返回一个 ifstream 实例以在另一个函数中使用

转载 作者:行者123 更新时间:2023-11-28 07:14:26 25 4
gpt4 key购买 nike

我将 ifstream 的开头分开,这样我就可以在不重新打开它的情况下循环遍历它,但不确定如何返回它以便它可以在另一个函数中使用。实际上,Npc_B_File 超出了第二个函数的范围。如何返回 ifstream?

void battle_start(char const* P_Name)
{
ifstream Npc_B_File(P_Name);
if(Npc_B_File.fail())
{
cout << "could not read file.";
}

}

void battle_npc(string npc)
{

while(btlcommand != npc)
{
Npc_B_File >> btlcommand;
}
if(btlcommand == npc_pick_dog)
Npc_B_File >> btlcommand;

if(btlcommand == "1" && bat_response == true)
{
cout << "You are in" << btlcommand;
Npc_B_File >> btlcommand;
bat_response = false;
}
if(btlcommand == "2" && bat_response == true)
{
cout << "You are in" << btlcommand;
Npc_B_File >> btlcommand;
bat_response = false;
}
if(btlcommand == "3" && bat_response == true)
{
cout << "You are in" << btlcommand;
Npc_B_File >> btlcommand;
bat_response = false;
}
}

最佳答案

选项 1

如果您的编译器和库支持 ifstream 的移动语义,您可以简单地使用:

ifstream battle_start(char const* P_Name)
{
ifstream Npc_B_File(P_Name);
if(Npc_B_File.fail())
{
cout << "could not read file.";
}
return Npc_B_File;
}

int main()
{
ifstream file(battle_start("filename"));
}

选项 2

对于不为 ifstream 实现移动语义的旧编译器或库,您可以使用:

void battle_start(char const* P_Name, /*out*/ifstream &Npc_B_File)
{
Npc_B_File.open(P_Name);
if(Npc_B_File.fail())
{
cout << "could not read file.";
}
}

int main()
{
ifstream file;
battle_start("filename", file);
}

关于c++ - 返回一个 ifstream 实例以在另一个函数中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20450482/

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