Skip lines in std::istream

30,963

Solution 1

Edit: You can also use std::istream::ignore, see https://stackoverflow.com/a/25012566/492336


Do I have to use getline the number of lines I want to skip?

No, but it's probably going to be the clearest solution to those reading your code. If the number of lines you're skipping is large, you can improve performance by reading large blocks and counting newlines in each block, stopping and repositioning the file to the last newline's location. But unless you are having performance problems, I'd just put getline in a loop for the number of lines you want to skip.

Solution 2

No, you don't have to use getline

The more efficient way is ignoring strings with std::istream::ignore

for (int currLineNumber = 0; currLineNumber < startLineNumber; ++currLineNumber){
    if (addressesFile.ignore(numeric_limits<streamsize>::max(), addressesFile.widen('\n'))){ 
        //just skipping the line
    } else 
        return HandleReadingLineError(addressesFile, currLineNumber);
}

HandleReadingLineError is not standart but hand-made, of course. The first parameter is maximum number of characters to extract. If this is exactly numeric_limits::max(), there is no limit: Link at cplusplus.com: std::istream::ignore

If you are going to skip a lot of lines you definitely should use it instead of getline: when i needed to skip 100000 lines in my file it took about a second in opposite to 22 seconds with getline.

Solution 3

Yes use std::getline unless you know the location of the newlines.

If for some strange reason you happen to know the location of where the newlines appear then you can use ifstream::seekg first.

You can read in other ways such as ifstream::read but std::getline is probably the easiest and most clear solution.

Share:
30,963
ufk
Author by

ufk

Programmer, Administrator, Gamer and Musician

Updated on January 14, 2020

Comments

  • ufk
    ufk over 4 years

    I'm using std::getline() to read lines from an std::istream-derived class, how can I move forward a few lines?

    Do I have to just read and discard them?

  • GManNickG
    GManNickG about 14 years
    Counting newlines is sorta what a looped getline would do, right?
  • Billy ONeal
    Billy ONeal about 14 years
    @GMan - Save the Unicorns: Yes, but you can use larger blocks and shift forward a larger distance if you know n is large (i.e. counting more than one newline in a buffer block)
  • ufk
    ufk about 14 years
    what if I'll load all the file to memory and parse it with regular expressions ? the file is less then 1MB.
  • Brian R. Bondy
    Brian R. Bondy about 14 years
    @Billy: Actually your tardiness gave me 10 extra rep since I was already at max cap until 10 min ago.
  • Billy ONeal
    Billy ONeal about 14 years
    LOL! I have yet to bump my head into said cap.