O
O
Oleg Andreev2020-12-02 07:12:54
C++ / C#
Oleg Andreev, 2020-12-02 07:12:54

How to rewrite integer elements from one file to another in c++?

There is a file:

cin >> n;
ofstream out;
out.open(“dsa.bat”, ios::binary);
for (int i=0; i < n; i++) {
    a = rand() % 25 + (-10);
    out.write((char*) & a, sizeof(int));
    ofstream out1(“dsa1.bat”, ios::binary);
    ofstream out2(“dsa2.bat”, ios:binary);
    if (a > 0 && a = 0) {
        out1 << a;
    }
    else {
        out2 << a;
    }
}
out.close();
out1.close();
out2.close();

Where "n" is the number of characters to be entered.
I apologize for the lack of an error handler.
I need to rewrite positive numbers from this binary to another file, for example "dsa1", and negative numbers to a third file.
I can't get it. Tried operator if (a > o) {s = a}. In this case, only the first element from the end (if it is positive) is put in s. While doesn't exit either. I want to sort it out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NIKITF, 2021-08-31
@NIKITF

Hello.
My solution to the problem using the string class:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
  ifstream Q("First.txt");
  ofstream Z("Second.txt");
  string temporary;
  while (Q >> temporary)       // извлекаем число из первого
  {
    Z << temporary << " "; // помещаем число во второй файл
  }
  Q.close(); Z.close(); return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question