我想在 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 << " ";
}
}
uj5u.com熱心網友回復:
也許嘗試呼叫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();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458897.html
上一篇:如何對檔案中的值求和并使用python中的新值更新檔案
下一篇:如何在顫振中打開pdf檔案?
