c++ - 为什么我的 getline() 不读取文件的空行?
问题描述
我正在编写一个函数来读取文件并显示除空行之外的每一行。但是,当我试图避免出现空行时,显示仍然包括每个空行。我的代码有什么问题?
ifstream rfile;
int lineNum{};
rfile.open(inputFilePath);
for (string line; getline(rfile, line);) {
lineNum++;
if (line.empty())
cerr << "Line " << lineNum << " is empty." << '\n';
else
cout << lineNum << ": " << line << '\n';
}
输入文件包含:
10* 8
44 - 88
12 + 132
70 / 7
有3条新线。但我的输出是:
1:
2:
3: 10* 8
4: 44 - 88
5: 12 + 132
6: 70 / 7
7:
为什么新线路还在显示?
cout << lineNum << ": " << line << '\n'; into cout << lineNum << ": " << line << ":" << line.length() << '\n';
正如@prehistoricpenguin 所说,我只是改变了。然后输出变成了:
:1
:1
:6
:8
:9
:7
:1
另外,我打开了“show whitesapce”。在我的输入文件中,它没有显示点或空格。然而,当运行程序时,点(空白)显示。
解决方案
\r\n
您的结果与使用 CRLF 样式 ( , 0x0D 0x0A
) 换行符的文本文件一致,但您的代码使用的std::getline()
实现仅识别 LF 样式 ( \n
, 0x0A
) 换行符,因此保留\r
在输出字符串中。这就是为什么length()
每个line
字符都比您预期的多 1 个字符的原因。
您需要在每次通话后检测并截断该额外\r
字符,例如:std::getline()
ifstream rfile;
int lineNum{};
rfile.open(inputFilePath);
for (string line; getline(rfile, line);) {
lineNum++;
if ((!line.empty()) && (line.back() == '\r'))
line.resize(line.size()-1);
if (line.empty())
cerr << "Line " << lineNum << " is empty." << '\n';
else
cout << lineNum << ": " << line << '\n';
}
推荐阅读
- list - 遍历列表中所有元组的函数 - Haskell
- c - 在c中使用条件变量
- wordpress - Wordpress REST api 最后一页
- php - 数据表状态保存搜索多输入但在表外
- javascript - 类型错误:voiceChannel.join 不是函数
- snowflake-cloud-data-platform - 雪花表中的数据是使用 AES 256 位还是 128 位自动加密的?
- angular - 大异步 GET 请求阻止浏览器中的另一个并行请求
- python - 如果在图像更改为下一个图像帧时保持显示上一个图像,如何修复逐帧动画?
- reactjs - 如何在 React 中使用 useReducer 钩子和异步数据?
- c - 为什么字符串比较不能按预期工作