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

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

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

8条回答
  •  -上瘾入骨i
    2020-12-31 03:58

    Call getline() once to throw away the first line

    There are other methods, but the problem is this, you don't know how long the first line will be do you? So you can't skip it till you know where that first '\n' is. If however you did know how long the first line was going to be, you could simply seek past it, then begin reading, this would be faster.

    So to do it the first way would look something like:

    #include 
    #include 
    using namespace std;
    
    int main () 
    {
        // Open your file
        ifstream someStream( "textFile.txt" );
    
        // Set up a place to store our data read from the file
        string line;
    
        // Read and throw away the first line simply by doing
        // nothing with it and reading again
        getline( someStream, line );
    
        // Now begin your useful code
        while( !someStream.eof() ) {
            // This will just over write the first line read
            getline( someStream, line );
            cout << line << endl;
        }
    
        return 0;
    }
    

提交回复
热议问题