每 X 行读取并写入文件

发布于 2025-01-01 23:41:48 字数 477 浏览 1 评论 0原文

#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;
}

我想让这个程序每 10 行读取一次并将其写入我的文件中。

我该怎么做呢?

#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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋凉 2025-01-08 23:41:48

您需要读取每一行并增加一个计数器。如果计数器达到 10,则需要写入该行并重置计数器。

       

int lineNumber = 0;

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

    lineNumber++;
}

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++;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文