2012-06-13 63 views
2

我想出了一個關於學習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()指針返回一塊內存和內存不連續的像一個數組,所以我不能遞增指針存儲卡。

我也試着計算文件中的行數(每行是一張卡片),然後製作一個這樣大小的數組,但是我得到的值不是常數。

什麼是最好的方式去存儲這些卡作爲集合?我只想讓這個集合成爲一個非常龐大的數組,但是我覺得這種情況經常出現在項目中,而寧願學習如何處理它,而不是輕鬆解決。

+0

switch語句出現在循環中的方式是一個衆所周知的反模式:http://en.wikipedia.org/wiki/Loop-switch_sequence –

回答

3

但是,如果我是正確的,malloc()函數返回一個指向內存 塊和內存不連續的像一個數組,所以我不能增加 指針存儲卡。

假。它是順序的。您可以使用malloc()創建的任何一個數組:

mystruct* ptr = (mystruct*) malloc(sizeof(mystruct) * numberOfStructs) 

for(int i = 0; i < numberOfStructs, i++) { 
    ptr[i].setSomeInfo(x); 
} 

這是做在C.

+0

事實證明,真正的問題是我的switch語句的默認部分從來沒有達到過,我一直在想,問題必須與指針(它會打印出隨機的東西,而不是卡),我甚至不認爲這是永遠不會被設置。感謝您的幫助,您的解決方案確實解決了問題。 – valon

1

標準的方式,我用在C很多,多到編程,我的最愛之一。這是我的答案。

你使用malloc的方式做了分配數組

struct card *collection = (struct card *) malloc(number_of_cards * sizeof(struct card)); 

對malloc每次調用將指向內存中返回不同的區域。但是一次調用malloc總是返回一個連續的塊。

如果卡的數量是已知的,你可以用它來分配數組,然後訪問它像這樣

//added some code to prevent overflow 
collection[i].name[255] = 0; 
strncpy(collection[i] .name, token, 255); 

如果不知道什麼的卡的數量。然後做一個鏈表。這是鏈接列表的主要用途,存儲大小未知的集合的內容。