Roll the Dice System

Hello Everyone!
I am now trying to find a way to create a way for users to Roll the Dice in the program after choosing a certain number of sides. Here is part of the code I am working with. Tell me if you come up with anything.

1
2
3
4
5
6
7
8
  if(input == "rtd")
            {
                std::cout << "rtd 'number of sides'" << std::endl;
            }
            else
            {
                std::cout << "An error has occured. Please enter 'help' for more." << std::endl;
            }
If you're talking about rolling dice, then I assume you want a random number (from 1 to the number of sides) to be generated.

The modern, C++11 way of doing it would be to use the features in the <random> header.
http://www.cplusplus.com/reference/random/ shows what's available.

Some of this get a bit hairy, but here's a basic example of. Don't worry if the syntax looks a bit disconcerting, it's mostly just boilerplate that you can copy.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <random>

int main() {
	std::default_random_engine generator;
	
	std::cout << "Enter number of sides: ";
	int sides = 6;
	std::cin >> sides;
	
	std::uniform_int_distribution<int> distribution(1, sides);
	
	int dice_roll = distribution(generator);  // generates number in the range 1..sides
	
	std::cout << "You rolled a " << dice_roll << '\n';
}
Topic archived. No new replies allowed.