我试图将一张牌如 "10""1""A "连接到字符串 "堆 "中。这是一个非常简化的21点版本,所以它不关心牌的花色,每次只发一张牌。
然而当我运行它的时候,它把牌加到了一个没有传入方法的牌堆字符串中。
我对这个问题做了一个最小的重现
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int placeCard(char *pile, char *card)
{
//removed code for minimal recreation of problem
//no piles finished
strcat(pile, card);
return 0;
}
int main()
{
char card[4];
char pile1[] = "";
char pile2[] = "";
char pile3[] = "";
char pile4[] = "";
char pile5[] = "";
char faces[13][4] = {" 2", " 3", " 4", " 5", " 6", " 7", " 8", " 9", " 10", " J", " Q", " K", " A"};
while(1)
{
// print current state of game
printf("Pile (1): %-20s \n", pile1);
printf("Pile (2): %-20s \n", pile2);
printf("Pile (3): %-20s \n", pile3);
printf("Pile (4): %-20s \n", pile4);
printf("Pile (5): %-20s \n\n", pile5);
//get random card
int j = rand() % 52;
//convert to string
strcpy(card, faces[j/4]);
printf("Drawn Card: %s\n\n", card);
printf("Which pile to place card in? ");
//assume valid input (1-5) for minmal reproduction of error
int userPileChoice;
scanf("%d", &userPileChoice);
switch (userPileChoice)
{
case 1:
placeCard(pile1, card);
break;
case 2:
placeCard(pile2, card);
break;
case 3:
placeCard(pile3, card);
break;
case 4:
placeCard(pile4, card);
break;
case 5:
placeCard(pile5, card);
break;
default:
break;
}
}
}
这里是输出
Pile (1):
Pile (2):
Pile (3):
Pile (4):
Pile (5):
Drawn Card: J
Which pile to place card in? 1
Pile (1): J
Pile (2): J
Pile (3):
Pile (4):
Pile (5):
Drawn Card: 7
Which pile to place card in?
我在想有可能是开关盒里面的while循环和break不知怎么搞的,但我试着研究了一下,没看出什么问题。谢谢大家的帮助。
这个。char pile1[] = "";
将分配一个大小为1的数组, 这只够NUL结束符使用, 这意味着它基本上是无用的. 对代码做如下修改。
#define SIZE 100
int main()
{
char card[4];
char pile1[SIZE] = "";
// Same for the rest
这样就可以解决你的问题了 但我建议阅读有关危险的 strcat
. 这里有一篇相关的文章。strcat Vs strncat - 什么时候应该使用哪个函数?它的工作原理是