C++ 流不读取空行

标签 c++ stream

我正在尝试编写一个函数,从一个 txt 文件中读取单独的行并将它们存储在一个字符串数组中。该函数正常工作,但读取空行时除外。示例:

函数

ifstream flinput( "somefile.txt" )
string line;

while( getline(flinput, line) ) {
  //Add line to array

所以问题是文本文件是否看起来像这样。

Line1 Some Text blar blar blar
\n
Line3 Some Text blar blar blar
\n
Line5 Some Text blar blar blar

数组最终看起来像这样。

array[0] = "Line1 Some Text blar blar blar"
array[1] = "Line3 Some Text blar blar blar"
array[2] = "Line5 Some Text blar blar blar"

什么时候应该看起来像这样。

array[0] = "Line1 Some Text blar blar blar"
array[1] = ""
array[2] = "Line3 Some Text blar blar blar"
array[3] = ""
array[4] = "Line5 Some Text blar blar blar"

我做错了什么?

谢谢

最佳答案

来自 getline 文档...

If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it. If you don't want this character to be extracted, you can use member get instead.

所以您的代码完全按照预期的方式工作。如果要保存\n,则必须按照文档的建议使用 Get 手动解析内容。

关于C++ 流不读取空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2006444/

相关文章:

node.js - 如何在nodejs中找到可读流的内容长度?

tomcat - 如何将 POST 数据从 servlet 读取到 ZipStream?

stream - webrtc 上的网络音频分析器用于远程流

c++ - 如何通过 C++ 使用 Google Translate API

c++ - 写入二进制文件

c++ - 用于检索 C++ 代码库中函数和方法列表的工具

windows - 在 Win32 GUI 应用程序中使用标准输出 : crashes if I don't have a redirect to file in arguments

c++ - 我可以将 Visual Studio 2005 设置为在调试时忽略特定代码区域中的断言吗

c++ - 在 C++ 中获取当前连接的网络名称 (SSID)

python - 如何在 Python 3 中将文本流编码为字节流?