当我调用另一个函数读取文本文件中的下几行时,如何使 getline 不跳过文本文件中的一行

How do I make getline not skip over a line from a text file when I call another function to read the next few lines in a text file

我正在尝试制作一个程序,该程序将从文本文件中读取输入并在检测到文本文件中的“1”时调用一个函数。当程序在文本文件中检测到“1”时,它会调用 ReadLines(fstream & file)。 Readlines() 然后将读取程序中接下来的 4 行。我遇到的问题是在调用 Readlines() 之后,main 中的循环不会读取文本文件中的下一行。它跳过它并继续读取在 main 中创建的 while 循环中的文件。

fstream file("paper.txt");
std::string str;

//Check if file is open
if (file.is_open()) {
    cout << "File is open" << endl;
}
else {
    cout << "File is not open" << endl;
    return 0;
}

//Get line from text file until it is at the end of file
while (std::getline(file, str)) {
    //Print the current line
    std::cout << str << endl;

    //If getline detects a "1", call ReadLines function
    if (str == "1") {
        cout << "---enter loop----" << endl;
        ReadLines(file);
    }
}

file.close();
return 0;

}

void ReadLines(fstream& file) {
int i = 1;
std::string str;

//Read the next 4 lines
while (std::getline(file, str) && i < 5) {
    std::cout << str << endl;
    i++;
}

cout << "--exit loop--" << endl;

}

这是文本文件的内容

1
234
10
12.5
tacos
1
123
12
23.22
cake

如您所见,“1”在文本文件中出现了两次。 ReadLines 函数内的循环似乎工作正常,但在循环回到主循环后,主循环没有检测到第二个“1”。它跳过它并且不调用 ReadLines 函数。

你在 ReadLines 中的 while 条件语句执行了 5 次。一旦 i == 1i == 2、...和 ​​i == 5。在最后一次执行时,它最终计算为 false,但只有在计算(执行)getline 之后,i < 5 才会计算为 false。您没有进入循环体,因此被读取的行被丢弃。

交换 && 周围条件语句的顺序,以便 i < 5 先计算,short circuits 并且在 i == 5 时不执行 getline