1

I am trying to copy 2 files into 1 file like ID1 . name1 . ID2 . name2 . but i cant do it...how am i supposed to copy each line from each file.

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


}
taufeeq zaman
  • 37
  • 2
  • 8

2 Answers2

6

First of all, read line by line.

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
    }
}
RAEC
  • 332
  • 1
  • 8
  • 1
    The trouble here is if that file2 is longer than file1 one it effectively truncates the output file to the size of file1. – Martin York Aug 06 '15 at 20:56
  • He can mod the code to his needs, im not gonna code it for him. And it seems to me he is building value pairs using both files, if one is shorter than the other he has to decide whether to stop or keep going, id think he stops but dont know his requirements – RAEC Aug 08 '15 at 12:34
0

I would just process each file separately into their own lists. After that put the contents of the lists into the combined 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] << " . ";
}
NeverAgain
  • 66
  • 1
  • 7
  • std::list has no [] operator. You are likely thinking std::vector. That said, there might be some performance advantages to using std::list and iterators. Also does not take into account the case of y.size() < x.size(). – user4581301 Aug 06 '15 at 21:14
  • i dont know how big the files are, but reading both files into memory before processing them does not seem efficient and can cause out of memory issues. – RAEC Aug 08 '15 at 12:35