在c++中逐行复制

Copy line by line in C++

本文关键字:复制 逐行 c++      更新时间:2023-10-16

我正在尝试将2个文件复制到1个文件中ID1。name1。ID2。name2。但是我做不到……我该如何从每个文件中复制每一行呢?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
 ifstream file1("ID.txt");
   ifstream file2("fullname.txt");
   ofstream file4("test.txt");
   string x,y;
  while (file1 >> x )
   {
       file4 <<  x <<" . ";
       while (file2 >> y)
       {
           file4 << y <<" . "<< endl;
       }
   } 

}

首先,逐行阅读。

ifstream file1("ID.txt");
string line;
ifstream file2("fulName.txt");
string line2;

while(getline(file1, line))
{
    if(getline(file2, line2))
    {
        //here combine your lines and write to new file
    }
}

我会把每个文件分别处理成它们自己的列表。然后将列表的内容放入组合文件中。

ifstream file1("ID.txt");
ifstream file2("fullname.txt");
ofstream file4("test.txt");
std::list<string> x;
std::list<string> y;
string temp;
while(getline(file1, temp))
{
    x.add(temp);
}
while(getline(file2, temp))
{
    y.add(temp);
}
//Here I'm assuming files are the same size but you may have to do this some other way if that isn't the case
for (int i = 0; i < x.size; i++)
{
    file4 << x[i] << " . ";
    file4 << y[i] << " . ";
}