C++语言读取了第一个文件之后,然后再读取第二个文件,两个文件变量混淆怎么办?怎么把第一个文件的内容和第二个文件的内容交换
第一个文件的内容存储在一个结构体中,然后再读取第二个文件时,将结构体中的值存储在另一个结构体中,这样就不会变量重复,二楼给的例子挺好的
ps:这个wu2019和2022真有意思 开小号恶意点踩
变量名字是不是重复了
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string file1Name = "file1.txt";
std::string file2Name = "file2.txt";
std::ifstream file1(file1Name);
std::ifstream file2(file2Name);//这里要有两个变量
if (!file1 || !file2) {
std::cout << "无法打开文件." << std::endl;
return 1;
}
std::string temp; // 用于缓存文件内容
// 读取第一个文件的内容到缓冲区
std::getline(file1, temp, '\0');
file1.close();
// 将第二个文件的内容写入第一个文件
std::ofstream output(file1Name);
output << file2.rdbuf();
output.close();
// 将缓冲区的内容写入第二个文件
std::ofstream output2(file2Name);
output2 << temp;
output2.close();
std::cout << "文件内容已交换." << std::endl;
return 0;
}