Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip lines in std::istream

Tags:

c++

istream

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?

like image 713
ufk Avatar asked Apr 05 '10 23:04

ufk


People also ask

How do I skip a line in C++?

The \n Character The other way to break a line in C++ is to use the newline character — that ' \n ' mentioned earlier.

Does Getline go to the next line?

getline(cin, newString); begins immediately reading and collecting characters into newString and continues until a newline character is encountered. The newline character is read but not stored in newString.


2 Answers

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.

like image 177
Arthur P. Golubev Avatar answered Nov 13 '22 04:11

Arthur P. Golubev


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.

like image 38
Billy ONeal Avatar answered Nov 13 '22 03:11

Billy ONeal