繁体   English   中英

为什么我的 getline() 不读取文件的空行?

[英]Why my getline() does not read empty lines of a file?

我正在编写 function 来读取文件并显示除空行之外的每一行。 但是,当我试图避免出现空行时,显示仍然包括每个空行。 我的代码有什么问题?

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条新线。 但我的 output 是:

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'; cout << lineNum << ": " << line << '\n'; into cout << lineNum << ": " << line << ":" << line.length() << '\n'; 正如@prehistoricpenguin 所说。 然后 output 变成:

:1
:1
:6
:8
:9
:7
:1

另外,我打开了“show whitesapce”。 在我的输入文件中,它没有显示点或空格。 然而,当运行程序时,点(空白)显示。

您的结果与使用 CRLF 样式( \r\n0x0D 0x0A )换行符的文本文件一致,但您的代码使用的std::getline()实现只识别 LF 样式( \n0x0A )换行符,因此在 output 字符串中留下\r 这就是为什么每linelength()比您预期的多 1 个字符的原因。

您需要在每次std::getline()调用后检测并截断额外的\r字符,例如:

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

这适用于带有 output 的 MSVC:

Line 1 is empty.
Line 2 is empty.
3: 10* 8
4: 44 - 88
5: 12 + 132
6: 70 / 7
Line 7 is empty.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM