首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回要在另一个函数中使用的ifstream实例

返回要在另一个函数中使用的ifstream实例
EN

Stack Overflow用户
提问于 2013-12-08 14:11:28
回答 2查看 74关注 0票数 0

我分离了ifstream的开口处,这样我就可以遍历它而不需要重新打开它,但是我不确定如何返回它,这样它就可以在另一个函数中使用。实际上,Npc_B_File超出了第二个函数的范围。如何返回ifstream?

代码语言:javascript
复制
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;
    }
}
EN

回答 2

Stack Overflow用户

发布于 2013-12-08 14:32:50

选项1

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

代码语言:javascript
复制
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实现移动语义的旧版编译器或库,您可以使用:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2013-12-08 14:32:42

你可能想要这样的东西:

代码语言:javascript
复制
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;
}

作为不相关的补充,代码如下:

代码语言:javascript
复制
btlcommand == "2" && bat_response == true

...makes你看起来像个笨蛋。只需使用:

代码语言:javascript
复制
btlcommand == "2" && bat_response
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20450482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档