Hello I have an assignment where I am supposed to generate random numbers. Then write them to a binary file. After that I am supposed to read the data print it to the screen. Then finally, I have to sort the data and output. I have to do that without using arrays. I was able to do the first two parts. However, I couldn't do the last part correctly, so I went to google and youtube looking for an illustration on how to do that, but I was out of luck. I would really love to know what is it that I am doing wrong, thank you.
I think I am supposed to use recursion fseek and casting to avoid using arrays; however, I don't know how to use them.
Here is my code along with the output:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
//Function prototypes
void Write_File(int num);
void Read_File(int num);
void Compare(int num);
//**********************
int main()
{
int num = 0;
cout << "Enter a positive number to generate random numbers ";
cin >> num;
Write_File(num);
Read_File(num);
Compare(num);
return 0;
}
//***************
// Functions Definitions
void Write_File(int num)
{
ofstream fout("sortfile.dat", ios::out | ios::binary | ios::beg);
int number = 0;
if (fout.is_open())
{
for (int x = 0; x < num; x++)
{
number = rand();
fout << number << endl;
}
fout.close();
}
else
{
cout << "Error, File not opened" << endl;
}
}
void Read_File(int num)
{
ifstream fin("sortfile.dat", ios::in | ios::binary | ios::beg);
int number = 0;
cout << endl << "randomly generated numbers befor sorting\n";
if (fin.is_open())//check first if open already
{
for (int i = 0; i < num; i++)
{
fin >> number;
cout << number << endl;
}
fin.close();
}
else
cout << "File not opened in read phase." << endl;
}
void Compare(int num)
{
int number = 0;
int temp = 0;
int hold = 0;
ifstream fin("sortfile.dat", ios::in | ios::binary | ios::beg);
if (fin.is_open())//check first if open already
{
for (int i = 0; i < num; i++)
{
fin >> number;
fin >> temp;
if (number > temp)
{
hold = temp;
temp = number;
number = hold;
}
else
{
ofstream fout("sortfile.dat", ios::out | ios::binary | ios::beg);
fout << number;
fout << temp;
}
ofstream fout("sortfile.dat", ios::out | ios::binary | ios::beg);
fout << number;
fout << temp;
}
cout << endl << "Nums after sort\n";
for (int i = 0; i < num; i++)
{
fin >> number;
cout << number << endl;
}
fin.close();
}
else
cout << "File not opened in read phase." << endl;
}
Output:
Enter a positive number to generate random numbers 4 randomly generated numbers befor sorting 41 18467 6334 26500 Nums after sort 6334 6334 6334 6334 Press any key to continue . . .