2012-06-13 65 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); 

如果不知道什么的卡的数量。然后做一个链表。这是链接列表的主要用途,存储大小未知的集合的内容。