首页 > 解决方案 > 当我调用另一个函数来读取文本文件中的下几行时,如何使 getline 不跳过文本文件中的一行

问题描述

我正在尝试制作一个程序,该程序将从文本文件中读取输入并在检测到文本文件中的“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 函数。

标签: c++loopsfilegetline

解决方案


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

交换您周围的条件语句的顺序,&&以便i < 5首先评估,短路并且不执行getlinewhen i == 5


推荐阅读