我想出了一個關於學習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 –