writing in 10 files and reading from them

Hey,

I am very new in programming and C++. My first task to learn is creating 10 random number generator and have 10 files. Write this 10 number (different numbers in every file) into 10 files. Later on, open the file and from the console read this. Until now, I have figured out for one file but I can't make for ten files. Here is my code;

#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<time.h>
using namespace std;

int main()
{
ofstream outputFile;
outputFile.open("0.dat");

int i, n;
time_t t;

n = 10;

/* Intializes random number generator */
srand((unsigned) time(&t));

/* Print 10 random numbers from 0 to 1023 */
for( i = 0 ; i < n ; i++ )
{
outputFile << rand() % 1023 << endl;

}
return 0;

}

Thanks

At the moment, you are writing 10 numbers into 1 file.

1
2
3
4
5
6
7
for( i = 0 ; i < n ; i++ ) 
{
    string fileName = to_string(i) + ".dat";
    ofstream outputFile(fileName);

    outputFile << rand() % 1023 << endl;
}

Make sure to #include <string>
http://www.cplusplus.com/reference/string/to_string/
Last edited on
You can use an array. Easy and simple.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main()
{
	ofstream outputFile[10];
	outputFile[0].open("0.dat");
	outputFile[1].open("1.dat");
	outputFile[2].open("2.dat");
	outputFile[3].open("3.dat");
	outputFile[4].open("4.dat");
	outputFile[5].open("5.dat");
	outputFile[6].open("6.dat");
	outputFile[7].open("7.dat");
	outputFile[8].open("8.dat");
	outputFile[9].open("9.dat");

	int i, j, n = 10;
	time_t t;

	/* Intializes random number generator */
	srand((unsigned) time(&t));

	/* Print 10 random numbers from 0 to 1023 */
	for(i = 0; i < 10; i++)
	{
		for(j = 0; j < n; j++)
		outputFile[i] << rand() % 1023 << endl;
	}

	for(i = 0; i < 10; i++)
		outputFile[i].close();

	return 0;
}
@integralfx
At the moment, you are writing 10 numbers into 1 file.


1
2
3
4
5
6
7
for( i = 0 ; i < n ; i++ ) 
{
    string fileName = to_string(i) + ".dat";
    ofstream outputFile(fileName);

    outputFile << rand() % 1023 << endl;
}


You forgot to close the file first before beginning to open a new file.
Topic archived. No new replies allowed.