Skip lines in std::istream

后端 未结 4 970
我在风中等你
我在风中等你 2021-01-12 03:05

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?

4条回答
  •  有刺的猬
    2021-01-12 03:16

    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::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.

提交回复
热议问题