nulled strings in struct

Hi all!

i am having quite a challenge with this program. when i run it it nulls out my strings. any input would be greatly appreciated.

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

#define DECKSIZE 53
int range_min= 1;
int range_max= 52;

struct DECK {
  string suit;
  int card;
  int psuit;
} cards [DECKSIZE];
void filldeck(void)
{
	int z= 1;
	for(int i = 1; i <=4 ; i++)
	{
		for(int j = 1; j <=13; j++)
		{
			cards[z].psuit = i;
			cards[z].card = j;
			if(cards[z].psuit == 1)
				cards[z].suit = "hearts";
			if(cards[z].psuit == 2)
				cards[z].suit = "diamonds";
			if(cards[z].psuit == 3)
				cards[z].suit = "clubs";
			if(cards[z].psuit == 4)
				cards[z].suit = "spades";
			z++;
		}
	}
}

void shuffle(void)
{
   // Generate random numbers in the half-closed interval
   // [range_min, range_max). In other words,
   // range_min <= random number < range_max
   int i = 0;
   while(i<1000)
   {
      int u = rand() % 52 + 1;
	  int v = rand() % 52 + 1;
      cards[0] = cards[v];
	  cards[v] = cards[u];
	  cards[u] = cards[0];
	  i++;

   }
   
}


int main ()
{
  filldeck();
  shuffle();
  for(int i=0; i<=5; i++)
  {
	  printf("%i %s",cards[i].card, cards[i].suit);
  }
  
}

Actually, the problem is with printf().

The printf() function expects the old "array of char" style strings, but you are giving it the address of an object. Try this instead:
printf( "%i %s ", cards[i].card, cards[i].suit.c_str() );

However, since this is C++, you shouldn't be using printf() at all. The best way is to say:
cout << cards[i].card << ' ' << cards[i].suit << ' ';

Hope this helps.
Topic archived. No new replies allowed.