soniccool
soniccool

Reputation: 6058

Read and Write into file every X line

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream  stream1("source.txt");
    string line ;
    ofstream stream2("target.txt");

        while( std::getline( stream1, line ) )
        {
            stream2 << line << endl;
            cout << line << endl;
        }


    stream1.close();
    stream2.close();    return 0;
}

I want to make this program read every 10th line and write it into my file.

How do i go about doing this?

Upvotes: 1

Views: 1919

Answers (1)

Fox32
Fox32

Reputation: 13560

You need to read every line and increment a counter. If the counter reach 10, you need to write the line and reset the counter.

       

int lineNumber = 0;

while( std::getline( stream1, line ) )
{
    if (lineNumber == 10)
    {
         stream2 << line << endl;
         cout << line << endl;
         lineNumber = 0
    }

    lineNumber++;
}

Upvotes: 3

Related Questions