首页 > 解决方案 > 为什么我的 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”。在我的输入文件中,它没有显示点或空格。然而,当运行程序时,点(空白)显示。

标签: c++c++11

解决方案


\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';
}

推荐阅读