每次调用该函数时,我都需要使用 getline() 。如何避免重复阅读 txt 中的相同行? C++

I need to use getline() every time the function is called. How to avoid repeating reading the same lines in txt? c++

我需要创建一个函数,每次单击按钮时,程序都会读取并根据 log_p.txt 文件中的一行进行操作。

但是,如果我把读取t的过程放在函数里面,每次都会读取第一行。

void ai_fight::getfile()
{
    std::ifstream t("log_p.txt");

    ui->pushButton->setEnabled(false);

    getline(t, rule);

    print_rule(rule);

    if(getline(t, p1hand)) print_p1hand(p1hand);

    if(getline(t, p1p)) print_p1p(p1p);

    if(getline(t, p2hand)) print_p2hand(p2hand);

    if(getline(t, p2p)) print_p2p(p2p);

    getline(t, announce);
    if(announce=="1 eliminated"||announce=="0 eliminated")
    {
        getline(t, buf);
        getline(t, buf);
        getline(t, buf);
        getline(t, buf);
        getline(t, win);
        print_win(win);
        ui->pushButton->setEnabled(true);
     }
     else if(announce=="0 winning"||announce=="1 winning")
     {
        ui->pushButton->setEnabled(true);
     }
     else qDebug()<<"----------announcement error"<<endl;
    ui->pushButton->setEnabled(true);
}

每次打开文件时,它都会从头开始读取。您需要的是在函数调用之间持久地记住文件中的当前位置。您可以(至少)通过两种方式实现它:

  1. 在函数外打开文件(例如作为 class 成员)。这样文件将在整个执行过程中打开,ifstream 对象将记住当前位置。

  2. 将文件中的当前位置存储在某个变量中。您可以使用 tellgseekg 方法来获取和设置文件流中的光标位置。当然你需要把这个值存储在函数外。

最简单的方法可能是将 ifstream 存储为 class 成员。

void ai_fight::getfile()
{
    if (!m_t.is_open())
         m_t.open("log_p.txt");
    ...

您可能想在到达 EOF 时关闭文件,以便循环。