【问题标题】:Why my getline() does not read empty lines of a file?为什么我的 getline() 不读取文件的空行?
【发布时间】:2021-04-03 03:22:00
【问题描述】:

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

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: 

为什么新行还在显示?

正如@prehistoricpenguin 所说,我刚刚更改了cout &lt;&lt; lineNum &lt;&lt; ": " &lt;&lt; line &lt;&lt; '\n'; into cout &lt;&lt; lineNum &lt;&lt; ": " &lt;&lt; line &lt;&lt; ":" &lt;&lt; line.length() &lt;&lt; '\n';。 然后输出变成了:

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

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

【问题讨论】:

  • 输入文件是否包含\r\n 行尾?
  • @Elijay 文件不包含 \r\n。我只是通过点击“enter”来添加新行来测试功能。
  • cout &lt;&lt; lineNum &lt;&lt; ": " &lt;&lt; line &lt;&lt; '\n';这一行改成cout &lt;&lt; lineNum &lt;&lt; ": " &lt;&lt; line &lt;&lt; ":" &lt;&lt; line.length() &lt;&lt; '\n';,就可以看到长度了
  • 这可能是一些跨平台问题造成的,比如说你在Windows上创建了输入文件,但是你的程序是在Linux上运行的。
  • 尝试在您选择的编辑器中打开Show whitespace,看看这些行是否实际上是空白的。

标签: c++ c++11


【解决方案1】:

您的结果与使用 CRLF 样式(\r\n0x0D 0x0A)换行符的文本文件一致,但您的代码使用了仅识别 LF 样式(\n、@ 987654325@) 换行符,从而在输出字符串中留下\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';
}

【讨论】:

  • 哇,我不知道有'\r'!非常感谢!
【解决方案2】:

这适用于 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.

【讨论】:

  • 是的,我正在使用 Clion,但得到了不同的答案......
猜你喜欢
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-19
  • 2015-04-03
  • 2021-02-18
相关资源
最近更新 更多