[英]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
I'm trying to make a program that will read input from a text file and call a function when it detects "1" in the text file.我正在尝试制作一个程序,该程序将从文本文件中读取输入并在文本文件中检测到“1”时调用 function。 When the program detects "1" in the text file, it will call ReadLines(fstream & file).
当程序在文本文件中检测到“1”时,它会调用ReadLines(fstream & file)。 Readlines() will then read the next 4 lines in the program.
然后 Readlines() 将读取程序中接下来的 4 行。 The problem I'm having is that after Readlines() is called, the loop inside main doesn't read the next line in the text file.
我遇到的问题是在调用 Readlines() 之后, main 内的循环不会读取文本文件中的下一行。 It skips over it and continues to read the file in the while loop created in 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;
} }
Here are the contents of the text file这是文本文件的内容
1
234
10
12.5
tacos
1
123
12
23.22
cake
As you can see, "1" is seen twice in the text file.如您所见,“1”在文本文件中出现了两次。 The loop inside the ReadLines function seems to work fine, but after the loop goes back to the main loop, the main loop doesn't detect the second "1".
ReadLines function 内的循环似乎工作正常,但循环返回主循环后,主循环没有检测到第二个“1”。 It skips over it and doesn't call the ReadLines function.
它跳过它并且不调用 ReadLines function。
Your while
conditional in ReadLines
is executed 5 times.您在
ReadLines
中的while
条件执行 5 次。 Once when i == 1
, i == 2
, ..., and i == 5
.当
i == 1
、 i == 2
、 ...和i == 5
时。 On the last execution it finally evaluates to false
, but only after getline
is evaluated (executed) does i < 5
get evaluated as false
.在最后一次执行时,它最终评估为
false
,但只有在getline
评估(执行)之后i < 5
才被评估为false
。 You don't enter the loop body, so the line that was read is discarded.您没有进入循环体,因此读取的行将被丢弃。
Swap the order of conditional statements around your &&
so that i < 5
evaluates first, short circuits and doesn't execute getline
when i == 5
.在
&&
周围交换条件语句的顺序,以便i < 5
首先评估,短路并且在i == 5
时不执行getline
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.