2010-01-05 44 views
1

我正在尝试编写一个函数,它读取txt文件中的各行并将它们存储在字符串数组中。除了读取空白行时,该函数可以正常工作。例如:C++流不读取空行

功能

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" 

我在做什么错?

由于

回答

3

从函数getline文档...

如果找到定界符,则提取并丢弃,即,它不被存储和之后的下一个输入操作将开始。如果你不想要这个角色被提取,你可以使用member get代替。

所以你的代码正在做它应该做的。如果要保存\ n,您必须使用Get手动解析事件,如文档所示。

+0

更简单的方法可以是将到阵列之前检查一个空字符串。如果字符串为空,则向数组追加一个“\ n”字符串。 – 2010-01-05 18:01:30

0

您的代码适用于Linux系统上的gcc 4.3.2。我认为它应该。

0

这将是简单的使用一个迭代,here's一个例子: