我分离了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;
}
}发布于 2013-12-08 14:32:50
选项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);
}发布于 2013-12-08 14:32:42
你可能想要这样的东西:
bool battle_start(char const* P_Name, std::ifstream &file) {
file.open(P_Name);
if(file.fail()) {
cout << "could not read file.";
return false;
}
return true;
}作为不相关的补充,代码如下:
btlcommand == "2" && bat_response == true...makes你看起来像个笨蛋。只需使用:
btlcommand == "2" && bat_responsehttps://stackoverflow.com/questions/20450482
复制相似问题