c++ - 当我调用另一个函数来读取文本文件中的下几行时,如何使 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 函数。
解决方案
您的while
条件输入ReadLines
执行了 5 次。一旦i == 1
, i == 2
, ..., 和i == 5
. 在最后一次执行时,它最终评估为false
,但只有在getline
评估(执行)之后才会i < 5
评估为false
。您没有进入循环体,因此读取的行将被丢弃。
交换您周围的条件语句的顺序,&&
以便i < 5
首先评估,短路并且不执行getline
when i == 5
。
推荐阅读
- google-bigquery - 附加辅助列时的 BigQuery GROUP BY 与 PARTITION BY
- python - 从 Python 中的字符串中提取抽象名词和形容词
- amazon-web-services - 当您将 Macbook 内容迁移到新 Mac 时,您的 AWS CLI 会发生什么情况?
- python - 如何在登录时验证用户名和密码,其中现有密码由存储在数据库中的 make_password 加密?
- node.js - Mongoose runValidators 无法使用 positional$ 处理 findOneandUpdate
- java - Flink 1.4.1 向 Job Manager 发送作业时随机响应 HTTP 500
- javascript - firebase web sign up with google 只有在第二次点击后才有效?
- python - 当输入是来自另一列的值时,将一列中的所有值作为 json 获取
- python - 过滤掉包含特定字符串的数据帧的行
- docker - 为什么docker在运行hello-world时显示连接超时错误?