Reputation: 573
So, I have this exercise here, what it is it's a quiz written in a file, each question has 2 answers and each question is in one line, where the last character before the newline is the correct answer. Given answers as well as the correct answers are separated with a '$'. This is how a sample file looks like:
Koja zemja koristi najmnogu elektrichestvo?$а)SAD$b)Kina$b
Koe e najchesto ime vo svetot?$a)Li$b)Muhamed$b
So, the program needs to print out one question along with both given answers, wait for an answer from stdin, and then check to see if the answer is correct. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
//if(argc!=2) {printf("Upotreba: ./2 <vlezna datoteka>"); return -1;}
FILE *read=fopen("kviz.txt", "r");
//if((read=fopen(argv[1], "r"))==NULL) {printf("Ne postoi takva datoteka."); return -1;}
int i=0;
int j;
char answer;
char string[200];
while(fgets(string, 200, read)!=NULL)
{
string[strlen(string)-1]='\0'; //remove newline
for(i=0;i<strlen(string);i++)
{
if(string[i]=='$') string[i]=' ';
}
for(i=0;i<strlen(string)-1;i++)
{
printf("%c", string[i]);
}
answer=getchar();
if(answer==string[strlen(string)-1]) {printf("Correct answer.\n"); continue;}
else {printf("Incorrect answer.\n"); continue;}
}
fclose(read);
return 0;
}
Now the program works for the first question, but it only lets me input an answer once. The output I get is:
Koja zemja koristi najmnogu elektrichestvo? а)SAD b)Kina b
Correct answer.
Koe e najchesto ime vo svetot? a)Li b)Muhamed Incorrect answer.
If you notice, after the second question I haven't inserted an answer, it just takes the answer i input first and compares it, and the comparison is bad as well since question 2 answer is also b and it prints that it is Incorrect. Any help?
Upvotes: 0
Views: 337
Reputation: 1334
getchar()
will get one character at a time.
When the user entering the answer and pressing enter, '\n' character is in the buffer.
So that the getchar()
get the '\n'
character when comes to second answer.
To avoid that,
put another getchar()
after this line. Like,
answer=getchar();
getchar();
It will take the newline and program will work fine.
Upvotes: 2