简体   繁体   English

跳过std :: istream中的行

[英]Skip lines in std::istream

I'm using std::getline() to read lines from an std::istream-derived class, how can I move forward a few lines? 我正在使用std :: getline()从std :: istream派生类中读取行,如何前进几行?

Do I have to just read and discard them? 我是否必须阅读并丢弃它们?

No, you don't have to use getline 不,您不必使用getline

The more efficient way is ignoring strings with std::istream::ignore 更有效的方法是使用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. 当然,HandleReadingLineError不是标准的而是手工制作的。 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 如果这恰好是numeric_limits :: max(),则没有限制: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. 如果您要跳过很多行,那么您绝对应该使用它而不是getline:当我需要跳过文件中的100000行时,使用getline花费的时间与22秒相反,大约需要一秒钟。

Edit: You can also use std::istream::ignore, see https://stackoverflow.com/a/25012566/492336 编辑:您也可以使用std :: istream :: ignore,请参阅https://stackoverflow.com/a/25012566/492336


Do I have to use getline the number of lines I want to skip? 我是否必须使用getline我要跳过的行数?

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. 但是除非您遇到性能问题,否则我只是将getline放在循环中,以获取要跳过的行数。

Yes use std::getline unless you know the location of the newlines. 是的,除非您知道换行符的位置,否则请使用std::getline

If for some strange reason you happen to know the location of where the newlines appear then you can use ifstream::seekg first. 如果由于某种奇怪的原因而碰巧知道换行出现的位置,则可以先使用ifstream::seekg

You can read in other ways such as ifstream::read but std::getline is probably the easiest and most clear solution. 您可以用其他方式阅读,例如ifstream::readstd::getline可能是最简单,最清晰的解决方案。

For what it's worth: 物有所值:

void skip_lines(std::istream& pStream, size_t pLines)
{
    std::string s;
    for (; pLines; --pLines)
        std::getline(pStream, s);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM