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; } } } 
2
  • 3
    Maybe have a look at std::getline. Commented Aug 6, 2015 at 20:28
  • OR you could use the tools that already do this. paste ID.txt fullname.txt > test.txt Commented Aug 8, 2015 at 14:32

2 Answers 2

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 } } 
Sign up to request clarification or add additional context in comments.

2 Comments

The trouble here is if that file2 is longer than file1 one it effectively truncates the output file to the size of file1.
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
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] << " . "; } 

2 Comments

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().
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.