tags:

views:

164

answers:

3

Hi,

I am trying to write a function that reads in individual lines from a txt file and stores them in a string array. The function works correctly except for when it reads in blank lines. Example:

Function

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

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

So the problem is if the text file looks like so.

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

The array ends up looking like this.

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

When it should look like this.

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"

What am I doing wrong?

Thanks

+3  A: 

From the getline documentation...

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.

So your code is doing exactly what it's supposed to. You'll have to manually parse things with Get as the documentation suggests if you want to save the \n.

cjserio
An easier method may be to check for an empty string before placing into the array. If the string is blank, append a string of "\n" to the array.
Thomas Matthews
A: 

Your code works for me with gcc 4.3.2 on a Linux system. I think it should.

A: 

It would be simpler to use an iterator, here's an example:

Liz Albin