在C中进行问答游戏

时间:2015-11-18 13:46:08

标签: c pointers struct

我试图在C中进行一个quizgame,我有一个问题和答案的文件格式如下:

爱丁堡在哪个国家?苏格兰;爱尔兰;英国;

文件中的每一行都有一个问题和三个答案,文件中的第一个答案始终是正确的。 我需要使用这样的结构:

typedef struct{
int answer1;
int answer2;
int answer3;
char*question;
}Questions;

我需要从文件中获取它们,所以我认为我应该创建一个循环,例如:

Questions q;
for(int i = 0; i < fileLength; i++){
 fscanf(file, "%s%d%d%d", &q.question, &q.answer1,&q.answer2, &q.answer3);
}

所以我需要遍历文件并为每个问题创建一个struct变量并给它赋值,然后将它放在一个数组中。我的老师告诉我使用多维数组,还有指针。我怎样才能以最好的方式实现这一目标?提前谢谢。

1 个答案:

答案 0 :(得分:0)

struct Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} book;  
   struct Books Book1;        /* Declare Book1 of type Book */
   struct Books Book2;        /* Declare Book2 of type Book */

   /* book 1 specification */
   strcpy( Book1.title, "C Programming");
   strcpy( Book1.author, "Nuha Ali"); 
   strcpy( Book1.subject, "C Programming Tutorial");
   Book1.book_id = 6495407;

   /* book 2 specification */
   strcpy( Book2.title, "Telecom Billing");
   strcpy( Book2.author, "Zara Ali");
   strcpy( Book2.subject, "Telecom Billing Tutorial");
   Book2.book_id = 6495700;

首先定义结构(如此处,顶部),

然后您可以将成员用作变量。有点像对象

一些资源:http://www.tutorialspoint.com/cprogramming/c_structures.htm

对于一些真实的代码:C, reading from file into structure