如何将2个数组字符串组成1个数组字符串,在那里我可以打印出所有52个扑克牌?
我的代码:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
int main() {
char deck[52];
char suits[] = {"Hearts","Diamonds","Clubs","Spades"};
char values[]= {"Ace","Two","Three","Four","Five","Six",\
"Seven","Eight","Nine","Ten","Jack",\
"Queen","King"};
int V, S, d = 0;
char string;
for ( S= 0; S <4; S++) {
for (V =0; V< 13; V++) {
string = strcat( values[V], suits[S]);
deck[d] = string;
printf("%s\n", string);//prints out all the 52 playing cards
d++;
}
}
return 0;
}
当我执行程序时,出现问题,要求我调试程序或关闭程序,最后我关闭了程序,没有返回任何内容。你能给我一个有效的答案吗?
答案 0 :(得分:1)
检查以下代码,修复代码中的问题: 你的代码的问题是你试图在打印之前修改实际的字符串,因此在下一次迭代中有一个修改过的字符串。所以只需将值和套装复制到数组并打印出来,如下所示。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<string.h>
int main()
{
int i=0;
char deck[30] = "";
char suits[][30] = {"Hearts","Diamonds","Clubs","Spades"};
char values[][30]= {"Ace","Two","Three","Four","Five","Six",
"Seven","Eight","Nine","Ten","Jack",
"Queen","King"};
int V, S;
for ( S= 0; S <13; S++)
{
for (V =0; V< 4; V++){
memset(deck,0,sizeof(deck));/* Clear the buffer before writing new value*/
strcpy( deck, values[S]);
strcat(deck,suits[V]);
printf("%s\n", deck);//prints out all the 52 playing cards
i++;
}
}
printf("Number of playing cards: %d\n",i);
return 0;
}
答案 1 :(得分:0)
strcat()
会返回char *
,指向char
的指针,而不是char
。
您甚至不需要考虑strcat()
的返回值,因为目标指针(第一个参数)现在将包含连接字符串,假设已经分配了足够的内存。
所以在你的代码中,你试图将连接的字符串放到values[V]
,当已经分配给它的内存不足时,这可能会失败。
最好的方法是分配一些内存(就像你对deck[]
所做的那样)并将其全部设置为零。然后保持strcat()
。
strcat(deck, values[V]);
strcat(deck, suits[S]);
答案 2 :(得分:0)
使用strcpy
和strcat
的替代方法是使用sprintf
。
#include<stdio.h>
#include<string.h>
#define NUM_SUITS 4
#define CARDS_PER_SUIT 13
#define TOTAL_CARDS (NUM_SUITS * CARDS_PER_SUIT)
int main()
{
char deck[TOTAL_CARDS][24];
char* suits[NUM_SUITS] = {"Hearts","Diamonds","Clubs","Spades"};
char* values[CARDS_PER_SUIT]= {"Ace","Two","Three","Four","Five","Six",
"Seven","Eight","Nine","Ten","Jack",
"Queen","King"};
int s, c, i;
for(s = 0; s < NUM_SUITS; s++)
{
for(c = 0; c < CARDS_PER_SUIT; c++)
{
sprintf(deck[(s * CARDS_PER_SUIT) + c], "%s of %s", values[c], suits[s]);
}
}
for(i = 0; i < TOTAL_CARDS; i++)
{
printf("%s\n", deck[i]);
}
return 0;
}