You asked how to concatenate two strings. You can use strcat
for this, but you must provide memory for it. You can allocate memory with malloc
, which means that you have to free it later. Or you can make the cards char arrays of a fixed size, which means that you have to copy around contents of char buffers with strcpy
when you exchange cards in your deck. Later, when you want to determine hands or compare suits and values, you have to compare partial strings, which is complicated.
So this is not an answer to your question, but a suggestion for a better approach to representing cards. I think strings are not a good representation of cards in a deck and therefore your question is headed in the wrong direction in the first place.
Consider making a card a struct of two enumerated values, the card's suit and rank:
enum Suit {
Hearts, Diamonds, Clubs, Spades, NSuit
};
enum Rank {
Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten,
Jack, King, Queen, NRank
};
#define NCard (NSuit * NRank)
struct Card {
enum Suit suit;
enum Rank rank;
};
Now it is easy to compare suits and ranks of cards or to sort them by value or to tell whether they are face cards.
There are several ways to print cards. I suggest a solution that fills a char buffer of a given maximum size:
static char *suit_name[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
static char *rank_name[] = { "Ace", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack","Queen", "King"
};
int cardstr(char *buf, size_t n, struct Card card)
{
return snprintf(buf, n, "%s of %s",
rank_name[card.rank], suit_name[card.suit]);
}
You can then pass that string to the %s
format of printf
later:
int main()
{
struct Card card[NCard];
int d = 0;
// Create deck in factory order
for (int s = 0; s < NSuit; s++) {
for (int r = 0; r < NRank; r++) {
card[d].suit = s;
card[d].rank = r;
d++;
}
}
// Print cards
for (d = 0; d < NCard; d++) {
char buf[20];
cardstr(buf, sizeof(buf), card[d]);
printf("%s\n", buf);
}
return 0;
}
(This is very similar to Bluepixie's answer, only much more long-winded.)