Rand in visual studio

Alright so I've recently began writing a card game program that stores cards in an array. I shuffle the deck by grabbing two cards randomly within the deck and swapping them. I do this several times in order to get a shuffled deck. Now this works perfectly fine in gcc. However, I moved my code over into visual studio and the cards shuffle but are shuffled the same way every time. It doesn't matter if I seed the randomizer or not. Either way, I get the same results every time. I'm not sure what the problem is. As I've said, my code works perfectly fine in gcc so I'm not exactly sure what the problem is. Any help would be appreciated. Thanks!
Last edited on
Can you repro your problem in a simple app? Basically, just the card shuffling, plus a bit of display code. And then post some C++ Shell friendly code?

Andy
Last edited on
Alright but I'm not sure what the outcome of the c++ shell will be. Like I said before... My code works in gcc but not in visual studio. Here it is:

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
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>

using namespace std;

class Deck {
public:
	string cards[52] = 
	
	{ "A\3", "2\3", "3\3", "4\3", "5\3", "6\3", "7\3", "8\3", "9\3", "10\3", "J\3", "Q\3", "K\3",
	"A\4", "2\4", "3\4", "4\4", "5\4", "6\4", "7\4", "8\4", "9\4", "10\4", "J\4", "Q\4", "K\4",
	"A\5", "2\5", "3\5", "4\5", "5\5", "6\5", "7\5", "8\5", "9\5", "10\5", "J\5", "Q\5", "K\5",
	"A\6", "2\6", "3\6", "4\6", "5\6", "6\6", "7\6", "8\6", "9\6", "10\6", "J\6", "Q\6", "K\6", };
	
	void shuffle();
	void print_cards();
};

void Deck::shuffle()
{
	for (int i = 0; i < 10; i++)
	{
		for (int index = 0; index < 52; index++)
			swap(cards[index], cards[rand() % 52]);
	}
}

void Deck::print_cards()
{
	for (int i = 0; i < 52; i++)
		cout << "Card " << i << ": " << cards[i] << endl;
}

int main()
{
        srand(time(0));
	Deck deck;
	deck.shuffle();
	deck.print_cards();
} 

Last edited on
Alright for some reason this works perfectly fine... even in VC. However, when I don't seed the randomizer, the cards are shuffled exactly like the other program. So I'm pretty sure VC is somehow missing the srand in my actual program. I don't get it.
Last edited on
Can you debug the call (or lack of call) to srand with MSVC?

Andy

PS You code runs fine on C++ Shell, though the little clubs and the like don't display. But the numbers look random.
Alright I've figured it out. I called the shuffle function within the constructor of Deck. Then I called srand in the main function. Now what really got me was that I declared a global Deck variable therefore shuffling the deck before even executing the main function.
Can you eliminate the need for a global?

Andy
Topic archived. No new replies allowed.