用c++编程实现将两个文本文件的内容连接成一个新的文件。
时间: 2024-02-13 15:06:26 浏览: 27
好的,这个问题我会尽力回答。以下是一个基本的C++程序,用于将两个文本文件的内容连接成一个新的文件:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string filename1, filename2, outFilename;
cout << "Enter the first input file name: ";
cin >> filename1;
cout << "Enter the second input file name: ";
cin >> filename2;
cout << "Enter the output file name: ";
cin >> outFilename;
ifstream file1(filename1);
ifstream file2(filename2);
ofstream outfile(outFilename);
string line;
while (getline(file1, line)) {
outfile << line << endl;
}
while (getline(file2, line)) {
outfile << line << endl;
}
file1.close();
file2.close();
outfile.close();
cout << "Files have been merged!" << endl;
return 0;
}
```
这个程序首先会要求用户输入三个文件名:要合并的两个输入文件和输出文件。然后,它会打开这三个文件,并将前两个文件的内容逐行读取并写入输出文件中。最后,程序关闭所有文件并输出一条合并完成的消息。
需要注意的是,这个程序只适用于文本文件。如果需要合并其他类型的文件,需要使用不同的方法。