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

时间:2013-12-08 06:11:28

标签: c++ ifstream

我将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;
    }
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

你可能想要这样的东西:

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

...让你看起来像一个普茨。只需使用:

btlcommand == "2" && bat_response