I have a .txt file named question.txt which contains the multiple-choice questions and multiple answers for them in this format :
**X question content
# Answer 1
# Answer 2
...
# Answer n
- X is an integer (a number of the chapter from which the question was taken)
- n is smaller or equal to 5
I'm trying to extract the information on the chapter number (X) the question content and the answers of said question and store them into a struct variable like so
struct {
int chapter;
int qcontent[512];
char answer[5][256];
}
Below is my attempt I was wondering if there is a different approach to this, maybe a more compact way ?
#include <stdio.h>
typedef struct {
int chapter;
char qcontent[512];
char answer[5][256];
} question;
int main()
{
question question[100];
FILE *fp = fopen("question.txt", "r");
char fline[512];
int i = -1; // Count question
int j = 0; // Count answer in a question
while (!feof(fp)) {
fgets(fline, 512, fp);
fline[strlen(fline) - 1] = 0;
if (strstr(fline, "**")) {
++i;
question[i].chapter = fline[2] - '0';
strcpy(question[i].qcontent, fline + 4);
j = 0;
}
if (strstr(fline, "#")) {
strcpy(question[i].answer[j++], fline + 2);
}
}
return 0;
}