How about
Code:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<string.h>
#define MAX_QUIZ 5
#define MAX_ARR 100
typedef struct quiz {
char question[MAX_ARR];
char answer[MAX_ARR];
} Quiz;
int initQuiz(Quiz *);
int main()
{
Quiz quiz[MAX_QUIZ] = { "", "" };
int correct = 0, wrong = 0, qindex, quizCtr = 0;
int answer;
char inputText[MAX_ARR] = { 0 };
srand(time(NULL));
if (!initQuiz(quiz))
printf("Error: Quiz Initialization Failed !");
else {
for (quizCtr = 0; quizCtr != MAX_QUIZ; quizCtr++) {
qindex = rand() % MAX_QUIZ;
printf("%s\nAnswer: ", quiz[qindex].question);
fgets(inputText, sizeof(inputText), stdin);
answer = strncmp(inputText,
quiz[qindex].answer, strlen(inputText) - 1);
switch (answer) {
case 0:
correct++;
break;
default:
wrong++;
break;
}
}
}
printf("Total Questions: %d\nCorrects: %d\nWrongs: %d\n",
MAX_QUIZ, correct, wrong);
return 0;
}
int initQuiz(Quiz * q)
{
FILE *file = NULL;
int ctr = 0;
char lineStr[MAX_ARR] = { 0 };
if (!(file = fopen("quiz.txt", "r")))
return 0;
else {
while (ctr < MAX_QUIZ &&
fgets(lineStr, sizeof(lineStr), file) != NULL) {
char *seppos = strstr(lineStr, "::"); /* find the separator */
if (seppos != NULL) {
int f1Len = seppos - lineStr; /* from start of line to :: */
int f2Len = strlen(seppos)-3; /* :: and a \n to omit from the length */
strncpy( q[ctr].question, lineStr, f1Len );
q[ctr].question[f1Len] = '\0';
strncpy( q[ctr].answer, seppos+2, f2Len );
q[ctr].answer[f2Len] = '\0';
ctr++;
}
}
}
fclose(file);
return 1;
}