Random Data Into Txt File

When I open the txt file, only one of the numbers is being recorded...but when I remove my file data...the 100 random numbers generate as meant to.

I am trying to generate 100 numbers from 100-200 into a txt file.

Thank you <3



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

#include "pch.h"
#include <iostream>
#include <fstream>



using namespace std;

int main()

{
	ofstream file;

	file.open("randomData.txt");

			
		srand((unsigned)(0));
		int ran_data;
		for (int index = 0; index < 100; index++) {
		ran_data = (rand() % 199) + 1;
		cout << ran_data << endl; }

	file << ran_data;
	
	file.close();
		
	return 0;

	}

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
39
40
41
42
43
44
45
#include <iostream>
#include <random>
#include <chrono>
#include <fstream>

int main()
{
   // create a random engine
   std::default_random_engine URNG { };

   // let's seed the sucker using a seed sequence
   // seed using either std::random_device or the system clock if random_device isn't available
   std::seed_seq::result_type seeds[] { std::random_device {}(),
                                        std::seed_seq::result_type(std::chrono::system_clock::now().time_since_epoch().count()) };

   // create the seed sequence
   std::seed_seq sseq(std::begin(seeds), std::end(seeds));

   // seed the random engine
   URNG.seed(sseq);

   // create a distribution 100 - 200 inclusive
   std::uniform_int_distribution<unsigned> DIST(100, 200);

   // how many random numbers do you want?
   const unsigned num_rnd { 100 };

   // open the file for writing
   std::ofstream file("test.txt");

   // skip count
   const unsigned count { 10 };

   for (size_t loop = 0; loop < num_rnd; loop++)
   {
      // get a random number
      unsigned num { DIST(URNG) };

      file << num << ' ';

      if (((loop + 1) % count) == 0) { file << '\n'; }
   }

   file.close();
}

(test.txt)
101 139 124 137 148 123 171 143 180 134 
122 192 190 106 169 154 189 154 174 171 
108 175 153 135 190 118 112 179 189 178 
195 177 104 136 137 113 177 155 170 163 
108 191 144 131 110 155 155 141 108 147 
128 200 108 168 116 144 145 109 111 195 
150 145 173 126 179 101 199 104 118 117 
139 186 129 197 117 181 151 132 167 103 
131 195 122 159 150 105 133 152 104 140 
106 154 139 196 142 128 120 136 191 185 
Line 24, where you write the random number to the file, is outside your loop. You write only one number to the file (reformatted source for clarity):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <cstdio>

int main()

{
   std::ofstream file;

   file.open("randomData.txt");

   std::srand(( unsigned) (0));
   int ran_data;

   for (int index = 0; index < 100; index++)
   {
      ran_data = (std::rand() % 199) + 1;
      std::cout << ran_data << '\n';
   }

   file << ran_data;

   file.close();
}


BTW, (std::rand() % 199) + 1 generates random numbers between 1 -198, not 100 - 200.

(std::rand() % 101) + 100 for 100 - 200.

I prefer using what C++11 offers for generating random number vs. the C library.
Last edited on
That was incredibly helpful! Thank you so much :) Also the fact that you said, "let's seed the sucker using a seed sequence" ...was enough to fully make my day haha. Now… BEAR with me (lol bears), what exactly does a -seed sequence- do? *hides behind curtain*

<3
It’s the number that is basically the starting point for URNG’s random numbers.
Okay, now I'm attempting to store the numbers from the file into an array and I'm pretty confused on my placement. Any advice or help is greatly appreciated.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
 

#include "pch.h"
#include <iostream>
#include <fstream>



using namespace std;

int main()

{
	ofstream file;		

	file.open("randomData.txt");	



			srand((unsigned)(0));  
			int ran_data;				

			for (int index = 0; index < 100; index++) { 

				ran_data = (rand() % 101) + 100;  
				
			}

		    file << ran_data;   //printing into text file
		   file.close();



			 int array[101] = {};		
		        ifstream is("ran_data");
		 	int num = 0;
			int x;

			while (num < array[101] && is >> x)
				array[num++] = x;

			cout << "The random numbers are:" << "\n";

			for (int i = 0; i < num; i++) {
				cout << array[i] << '  ';

			}

			is.close();

		return 0;

	}
what exactly does a -seed sequence do?

A seed sequence is a sequence of integer numbers that are used to seed a C++11 random number engine.

http://www.cplusplus.com/reference/random/seed_seq/
https://en.cppreference.com/w/cpp/numeric/random/seed_seq

It is not a single number.
BTW, I hope you realize if you were actually writing 100 3-digit random numbers to a file they would be all schmooshed together. Your file will appear to contain a single 300-digit number. Trying to read that into an int will not work as you expect.

You are still writing only one number to your file, the last one generated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <cstdio>

int main()

{
   std::ofstream file;

   file.open("randomData.txt");

   std::srand(( unsigned) (0));

   for (int index = 0; index < 100; index++)
   {
      int ran_data = (std::rand() % 101) + 100;

      file << ran_data << '\n'; // <-- notice writing to the file is INSIDE the loop!!!!!!
   }

   file.close();
}


Learning to use vectors might serve you better than a C style array also when you read the numbers back from the file.

For that matter you could use a vector to hold your created random numbers and then write the container's elements to the file.
@Furry Guy

Thank you so much for that. It's appreciated :) I didn't even realize I had the writing outside of the loop. I've been studying pretty much non-stop so it starts to get a little fuzzy.

This is what I have now with the array added after some editing from help and advice. I think it's running correctly now.

I haven't learned vectors yet so I'll start reading on them now.

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
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "pch.h"
#include <iostream>
#include <fstream>



using namespace std;

int main()
{
	ofstream file;

	file.open("randomData.txt");


	srand((unsigned)(0));
	int ran_data;

	for (int index = 0; index < 100; index++) 
	{

		ran_data = (rand() % 101) + 100;
		file << ran_data << endl;

	}

	file.close();



	int array[101] = {};
	ifstream is("randomData.txt");
	int num = 0;

	while (num < 100)
	{
		is >> array[num++];
	}

	cout << "The random numbers are:" << "\n";

	for (int i = 0; i < num; i++) {
		cout << array[i] << ' ';

	is.close();
}

 return 0;

}
Last edited on
Using vectors instead of C style arrays:
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <fstream>
#include <cstdlib>  // srand/rand
#include <ctime>    // time
#include <vector>

int main()
{
   const unsigned num_elems = 100;

   std::srand((unsigned) std::time(0));

   // Arise vector, I invoke thee! (empty)
   std::vector<int> vec;

   for (size_t index = 0; index < num_elems; index++)
   {
      // create a random number and cram it back into the vector
      vec.push_back((std::rand() % 101) + 100);
   }

   // did we actually get 100 numbers?  let's check
   for (size_t loop { }; loop < num_elems; loop++)
   {
      std::cout << vec[loop] << ' ';
   }
   std::cout << "\n\n";

   std::cout << "Let's see that again (using iterators):\n";
   for (auto it = vec.begin(); it != vec.end(); it++)
   {
      std::cout << *it << ' ';
   }
   std::cout << "\n\n";

   std::cout << "Let's try a range based for loop:\n";
   for (auto& it : vec)
   {
      std::cout << it << ' ';
   }
   std::cout << "\n\n";

   std::cout << "Let's write our stored data out to a file:\n\n";

   std::fstream file("randomData.txt", std::fstream::out); // assume the file opened OK

   for (auto& it : vec)
   {
      file << it << ' ';
   }

   // done writing to the file, let's close it
   file.close();

   // open the file for reading
   file.open("randomData.txt", std::fstream::in);

   // we can either clear the vector of its contained data
   vec.clear();

   // or create a new vector
   std::vector<int> vec_in;

   // let's use the cleared vector for reading the data
   int temp;
   while (file >> temp)
   {
      vec.push_back(temp);
   }

   std::cout << "The data file contains:\n";
   for (auto& it : vec)
   {
      std::cout << it << ' ';
   }
   std::cout << '\n';
}
Furry Guy! "Arise vector, I invoke thee! (empty)"

omg you're hilarious and you made vectors look super cool and much easier to follow & understand than the professors I've had. I wish you were my teacher. *sad face*

Thank you for taking the time to show me that :)
Learning should be fun, and so should teaching. When I create a code example for someone here I most times add far more comments than I normally would.

It is my "Lucy 'splainin'" method.

If the instructor is bored by the material, why should the students care? (Hint, they don't.)

Please notice I not only showed you how to use vectors, I also showed you several different ways to "walk through" the container.

I'm subtle that way. Sneak up behind ya, and then slam you upside your head with additional C++ features that make using what you did ask about easier.

Too often instructors are given a book/guideline of how and what to teach that is years outdated. Written by people who don't know how the language has evolved.

Current C++ is not C. Nor is it C++98.

C++20 is about to be finalized. Why ignore C++11/14/17 features that make writing code MUCH easier?

Writing programs as if the language were stone knives and bear skins is IMO stupid.

I am not a professional C++ coder. For me this is a hobby. I am learning what C++ can do as well.

There are people here who code professionally. When they offer up a code snippet they are really using well what C++ has to offer, though in different areas.

Two people who I've personally learned a lot from are JLBorges and Duthomas.

There are others, but those two have really challenged me to examine their code snippets and dissect them.
Last edited on
Registered users can post here. Sign in or register to post.