Little help understanding function

just wanted to a function to print my dice rolls.
But for some reason, it dosen't print anything.
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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

void rollDice(int rollResults[])
{
	srand(unsigned int(time(0)));
	rollResults[3];
	for (int i = 1; i <= 3; i++)
	{
		rollResults[i] = rand() % 6 + 1;
		cout << rollResults[i] << "\n";
	}
}
void printRoll()
{
        int user[3];
	rollDice(user);
}

int main()
{
        printRoll;
}
Last edited on
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
#include <iostream>                     // Is it too much to ask for your headers?
#include <cstdlib>
#include <ctime>
using namespace std;

void rollDice(int rollResults[])
{
	srand((unsigned int)time(nullptr));    // rewritten
	// rollResults[3];                     // No, No, No!
	for (int i = 0; i < 3; i++)            // <3 , not <= 3
	{
		rollResults[i] = rand() % 6 + 1;
		cout << rollResults[i] << "\n";    // This would be better in the calling function
	}
}

void printRoll()
{
	int user[3];
	rollDice(user);
	// Your output really ought to go here ...
}

int main()
{ 
    printRoll();      // <====== Proper function call
}
Modified to use modern C++ for generating random numbers and containers:
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
#include <iostream>
#include <random>
#include <vector>

void rollDice(std::vector<int>& rolls)
{
   // create a pre-defined random engine
   // seeding it with the non-deterministic random engine
   std::default_random_engine rng(std::random_device {} ());

   // create a distribution to simulate a die's pips
   std::uniform_int_distribution<int> dis(1, 6);

   // 'cast the die' for each element in the vector
   for (size_t itr { }; itr < rolls.size(); ++itr)
   {
      rolls[itr] = dis(rng);
   }
}

void printRoll()
{
   // create a vector of known size
   std::vector<int> rolls(3);

   rollDice(rolls);

   // use a range-based for loop to iterate through the vector
   for (const auto& itr : rolls)
   {
      std::cout << itr << ' ';
   }
   std::cout << '\n';
}

int main()
{
   printRoll();
}

http://www.cplusplus.com/reference/random/

If'n a time based seed is preferred #include <chrono> and modify line 9 to:
9
10
   std::default_random_engine rng(
      static_cast<unsigned>(std::chrono::system_clock::now().time_since_epoch().count()));
Topic archived. No new replies allowed.