Reputation: 27
First time using C, it's for an assignment at uni. Have to make a simple quiz program that reads from text files that are in the format of:
Question
Number of choices
Choice 1
Choice 2
...
Actual Answer
Question
Number of choices
...
For some reason, no matter how I fiddle and play with the variables, I cannot get the two character arrays, the actual answer and the typed answer, to be recognised as equal. Please tell me where I've messed up (probably an awful lot of places, considering it was my first shot at C) Thanks in advance, and here is my code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* readnextln(FILE *stream);
void writenextln(FILE *stream);
int main(){
char currentstring[512], answer[512], preanswer[512], playeranswer[512];
int i, cor, tot, ansnum;
printf("\nWelcome to the quiz program!\n");
printf("Type 'Exit' at any time to quit!\n\n");
FILE *fp = fopen("questions.txt", "r");
do {
writenextln(fp); //Question
ansnum=0;
strcpy(currentstring,readnextln(fp)); //Read line
if (feof(fp)==0){
ansnum=atoi(currentstring); //If the file hasn't ended, this line is the number of answers.
for (i=0;i<ansnum;i++){
writenextln(fp); //Write that many next lines.
}
strcpy(preanswer,readnextln(fp)); //Store the next line as the answer
strncpy(answer, preanswer, strlen(preanswer)-1); //Remove trailing newline character
printf("\n");
scanf("%s",playeranswer); //Get player's answer
if (playeranswer=="exit"){
printf("You scored %d/%d!",cor,tot);
exit(0); //If rthey say exit, exit
}
else{
cor+=checkcorrect(playeranswer==answer,answer); //Otherwise, check correctness and do things accordingly
tot++;
}
}
}
while (feof(fp)==0);
fclose(fp);
printf("You scored %d/%d!",cor,tot);
exit(0);
}
char* readnextln(FILE *stream){
char tempstring[5000];
fgets(tempstring,5000,stream);
return tempstring;
}
void writenextln(FILE *stream){
char tempstring[5000];
fgets(tempstring,5000,stream);
printf(tempstring);
}
int checkcorrect(int yes, char *ans){
if (yes==1){
printf("Correct!\n\n\n");
return 1;
}
else{
printf("Incorrect! The answer is %s!\n\n\n",ans);
return 0;
}
}
Upvotes: 0
Views: 90
Reputation: 138061
You're comparing pointer values, not the values they point to. Pointer comparison holds true if the memory address they contain is the same. To compare string equality, use strcmp
or strncmp
.
Additionally:
char* readnextln(FILE *stream){
char tempstring[5000];
fgets(tempstring,5000,stream);
return tempstring;
}
This is undefined behavior (in other words, the worst kind of illegal). You are returning a pointer to local memory, whose data is likely to be overridden and filled with garbage after the next function call (any function call).
Upvotes: 3