user174084
user174084

Reputation: 1107

C++ Streams Not Reading Blank Line

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

Upvotes: 1

Views: 588

Answers (3)

Liz Albin
Liz Albin

Reputation: 1489

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

Upvotes: 0

user231967
user231967

Reputation: 1975

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

Upvotes: 0

cjserio
cjserio

Reputation: 2897

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.

Upvotes: 3

Related Questions