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

后端 未结 8 1657
野趣味
野趣味 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<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.

    0 讨论(0)
  • 2020-12-31 04:15
    #include <fstream>
    #include <iostream>
    using namespace std;
    
    int main () 
    {
      char buffer[256];
      ifstream myfile ("test.txt");
    
      // first line
      myfile.getline (buffer,100);
    
      // the rest
      while (! myfile.eof() )
      {
        myfile.getline (buffer,100);
        cout << buffer << endl;
      }
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题