我正在尝试创建一个简化版的鲁米牌游戏。我需要在卡片中解析缩写,例如SA是黑桃Ace。DT是钻石10等等,我知道有一个更容易的方法来做到这一点,但这是我的任务,希望它完成。
示例执行将类似于
瘤胃3 S2 H9 C4.等包括所有52张卡。
argv1中的数字是游戏中的玩家。我该如何从数字开始,把卡片放进数组中呢?
到目前为止我的代码
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int players = *argv[1];
char deck[52];
int i, j, pid, cid;
if (players > '5' || players < '3')
{
printf("%c is not the allowed number of players, min is 3 and max is 5\n",*argv[1]);
exit(0);
}
}发布于 2016-02-24 08:20:12
快速而肮脏的示范:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int players = atoi(argv[1]);
char deck[52][3];
int i, j, pid, cid;
if (players > 5 || players < 3)
{
printf("%d is not the allowed number of players, min is 3 and max is 5\n", players);
exit(0);
}
for (i = 0; i < argc - 2; i++)
{
strcpy(deck[i], argv[i+2]);
}
for (i = 0; i < argc - 2; i++)
{
printf("%s\n", deck[i]);
}
}绝对不对输入进行理智检查。只是为了演示。
发布于 2016-02-24 08:30:36
int argc是参数的计数。因此,如果您愿意,可以手动将所有这些卡加载到数组中。
假设您像这样执行程序:
example.exe rummy 3 S1 S2 S3 S4 A1 A2 A3 A4然后,您可以将卡片读入这样的数组中(假设"rummy“是游戏类型,而"3”是其他控制变量,则需要确保这一点)
int main(int argc, char *argv[])
{
char game[10] = argv[0];
int players = atoi(argv[1]);
char deck[52][3]; // an array of strings max lenght 3 (2 characters + required '\0' terminator
for (int i = 0; i < argc - 2; i++) // argc - 2 because we're accessing at i+2 so the last iteration will essentially access the last element
{
strcpy(deck[i], argv[i+2]); // copy into actual array
}
return 0;
}现在,你把你的卡片放在一个称为“甲板”的字符数组中。请注意,这只是一个完整的样本,不建议直接使用。在最终程序中,您必须对所有可能的情况(过多的args、过少的args、错误的args等)进行理智检查和验证。
发布于 2016-02-24 08:11:55
传递给命令行的所有参数都存储在argv数组中。argv[0]始终是程序的名称,如果有参数的话,接下来是参数(以空结尾的字符串)。
因此,假设您已经将其称为:
瘤胃3 S2 H9 C4
这就是argv所包含的内容:
argv[0] = "rummy"
argv[1] = "3"
argv[2] = "S2"
argv[3] = "H9"
argv[4] = "C4"将这些内容插入数组很简单:
char args[5][10];
strncpy(args[0], argv[0], 10);https://stackoverflow.com/questions/35596448
复制相似问题