简体   繁体   中英

How do you swap integers between two files?

I want to copy integers from file A to file B and then from B to A in c++. There is integers 1 2 3 4 5 in file A and B is empty. After running the program file B consists of integers 1 2 3 4 5 while file A is empty somehow. I tried using.clear() and.seekg(0) but it was useless. What have I done wrong?

#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 << " ";
    }
}

Maybe try calling close() on the streams in between to ensure the pending output is written out before the new streams are opened:

#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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM