如何在两个文件之间交换整数?
How do you swap integers between two files?
我想在 C++ 中将整数从文件 A 复制到文件 B,然后从 B 复制到 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()
以确保在打开新流之前写出挂起的输出:
#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();
}
我想在 C++ 中将整数从文件 A 复制到文件 B,然后从 B 复制到 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()
以确保在打开新流之前写出挂起的输出:
#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();
}