Random Numbers and writing to a fileSolutionPlease find the
Random Numbers and writing to a file
Solution
Please find the required program along with its output. Please see the comments against each line to understand the step.
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
srand(time(NULL)); // Seed the time
char data[100];
ofstream outfile;
outfile.open(\"random.txt\"); // open the file random.txt in write mode.
for(int i=1; i<=100; i++) {
int randNum = rand()%(49-20)+20; // Generate a random number in the range 20-49
outfile << randNum << endl; // write the random number into the file.
}
cout << \"Writing to file completed!\ \" << endl;
outfile.close(); // close the opened file.
return 0;
}
---------------------------------------------------------------
OUTPUT:
sh-4.3$ main
Writing to file completed!
sh-4.3$ cat random.txt
22
34
45
32
31
30
42
38
.
.
.
.
.
