How do I read a text file from the second line using fstream?

后端 未结 8 1701
野趣味
野趣味 2020-12-31 03:19

How can I make my std::fstream object start reading a text file from the second line?

8条回答
  •  感动是毒
    2020-12-31 04:12

    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.

提交回复
热议问题