Randomize using class

Apr 10, 2009 at 12:55am
I am trying to make a loop and get a diferent number every time from a class.But, I am getting always the same number. What is the problem?

#include <iostream>
#include <cstdlib>
#include<ctime>
using namespace std;

class dic
{
public:

int sort()
{
srand(time(0));
return (rand() % 3)+1;

}
};

int main()
{dic dice;
int points=0;

for (int i=0;i<10;i++)
{
points=dice.sort();
cout<<points;
}
}
Apr 10, 2009 at 12:58am
Only call srand() ONCE. i.e. put it as the first thing you do in main.
Apr 10, 2009 at 1:09am
Thanks,

The problem is that I am not able to put srand() in main, this is an exercise where I was told not to change main function, I can only work on the class.
Apr 10, 2009 at 1:16am
Hmm...then you could try setting a global bool that tells you whether you have set srand() or not, then check that.
Apr 10, 2009 at 1:18am
I added a new function on the class, that I called void random() , and put the srand() on the function, that solved the problem. Thanks, you gave me some direction on the solution!
Apr 10, 2009 at 2:50am
Ah, yeah, that would work, and would probably work better.
Topic archived. No new replies allowed.