[英]How do you swap integers between two files?
我想将整数从文件 A 复制到文件 B,然后从 B 复制到 c++ 中的 A。文件 A 中有整数 1 2 3 4 5,B 为空。 运行程序后,文件 B 由整数 1 2 3 4 5 组成,而文件 A 不知何故为空。 我试过使用 .clear() 和 .seekg(0) 但没用。 我做错了什么?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream A1;
ofstream B1;
ifstream B2;
ofstream A2;
A1.open("C:\\Users\\User\\Desktop\\A.txt");
B1.open("C:\\Users\\User\\Desktop\\B.txt");
int ch;
while (A1 >> ch)
{
B1 << ch << " ";
}
A2.open("C:\\Users\\User\\Desktop\\A.txt");
B2.open("C:\\Users\\User\\Desktop\\B.txt");
/*B1.clear();
B2.clear(); ///didn't work
B2.seekg(0);*/
while (B2 >> ch)
{
A2 << ch << " ";
}
}
也许尝试在其间的流上调用close()
以确保在打开新流之前写出挂起的 output:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream A1;
ofstream B1;
A1.open("C:\\Users\\User\\Desktop\\A.txt");
B1.open("C:\\Users\\User\\Desktop\\B.txt");
int ch;
while (A1 >> ch)
{
B1 << ch << " ";
}
A1.close();
B1.close();
ifstream B2;
ofstream A2;
A2.open("C:\\Users\\User\\Desktop\\A.txt");
B2.open("C:\\Users\\User\\Desktop\\B.txt");
while (B2 >> ch)
{
A2 << ch << " ";
}
A2.close();
B2.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.