Dice Game

I have this dice game and it has the user input the number of sides on the di. When I debug it it prints the cout statement twice and I am confused. Where is my mistake? (Also, I borrowed this from someone else and it is their work)

#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <time.h>
using namespace std;

class Game1
{
private:

int dice;
int Value;

public:
Game1()
{
srand(time(NULL));
roll();
}

void roll()
{
int n;
cout << "Enter the number of sides on your Di: ";
cin >> n;
dice = (rand() % n) + 1;
setdice();

}

void setdice()
{
Value = dice;
}

int getdice()
{
return Value;
}

void display()
{
cout << "The Di rolled a " << getdice() << "." << endl;
}
};

int _tmain(int argc, _TCHAR* argv[])
{
Game1 G1;
G1.roll();
G1.display();
return 0;
}

Because, roll() is called once in the class' constructor, so its called once when you create G1. Then again you call G1.roll(). So you see it two times. To fix this just remove G1.roll().

Also since you are using srand() and rand() you need to add #include <cstdlib> too.
Last edited on
Wow. Eureka. It works. Thanks Storm.
Last edited on
Topic archived. No new replies allowed.