我想出了一个关于学习C的项目,而且我碰到了一堵墙。 该项目只是一个纸牌游戏,玩家有两套牌,一套是一套尺寸的套牌,另一套是可以像需要的那样大的牌的集合。 卡结构如下:如何存储从C文件中读取的结构?
struct card {
char name[256];
char special[256];
char type[100];
char rarity[100];
int points;
};
然后我有一个名为coll.txt
first card goes here 50
second card goes here 70
...
然后我有一个(马虎)函数从文件,并将其存储读取收集的文件成临时卡:
void read_into_collection(FILE *f) {
char *file_text;
char *token;
int i;
struct card temp;
file_text = (char *) malloc(sizeof(struct card));
while(fgets(file_text, sizeof(struct card), f)) {
for(i = 1, token = strtok(file_text, " "); token; i++, token = strtok(NULL, " ")) {
switch (i) {
case 1:
strcpy(temp.name, token);
break;
case 2:
strcpy(temp.special, token);
break;
case 3:
strcpy(temp.type, token);
break;
case 4:
strcpy(temp.rarity, token);
break;
case 5:
temp.points = atoi(token);
break;
default:
i = 0;
break;
}
}
}
free(file_text);
}
所以由我准备临时卡的下一张牌移动到收集并读入德时间i = 6
mp变量等等。但我该怎么做?我无法弄清楚收集应该是什么样的。起初我以为:
struct card *collection = (struct card *) malloc(number_of_cards * sizeof(struct card));
但是,如果我是正确的,malloc()
指针返回一块内存和内存不连续的像一个数组,所以我不能递增指针存储卡。
我也试着计算文件中的行数(每行是一张卡片),然后制作一个这样大小的数组,但是我得到的值不是常数。
什么是最好的方式去存储这些卡作为集合?我只想让这个集合成为一个非常庞大的数组,但是我觉得这种情况经常出现在项目中,而宁愿学习如何处理它,而不是轻松解决。
switch语句出现在循环中的方式是一个众所周知的反模式:http://en.wikipedia.org/wiki/Loop-switch_sequence –