Copy line by line in C++
本问题已经有最佳答案,请猛点这里访问。
我正在尝试将两个文件复制到一个文件中,就像ID1。名字1。ID2。名字2。但我做不到……我该如何从每个文件中复制每一行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | #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; } } } |
首先,逐行阅读。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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 } } |
我只需将每个文件单独处理到它们自己的列表中。然后将列表的内容放入组合文件中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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] <<" ."; } |