#remade the CLI quiz, stuck at scoring system
38 messages · Page 1 of 1 (latest)
So the strcpsn in CheckAnswer is illegal right now. Your string is uninitalized at that point. Why not use fgets instead? You do it properly in the do while loop at the end
As for checking if the user got it right, this is where a return value is handy:
#include <stdbool.h>
bool CheckAnswer(char *Question, char *Correct) {
...
if (strcmp(Answer, Correct) == 0) {
puts("correct!");
return true;
} else {
puts("incorrect");
return false;
}
}```
Then later you can do like
if (!CheckAnswer(...)) {
// the user got it wrong
}```
whats wrong with strcspn? you mean scanf?
char Answer[100];
strcspn(Answer, "\n") // illegal because your array is uninitialized```
score++;
}
CheckAnswer("What is the capital of Turkey?\n", "Ankara", score);
CheckAnswer("What is the denary equivalent of 1101?\n", "13", score);
CheckAnswer("When did WWII end?\n", "1945", score);
problem is I want to increment my score variable each time a question has been answered correctly
but I still need to add an argument inside that function which is inside the if statement
isnt there a way to make a variable (or a pointer) that holds the function
You know if the question was answered correctly if the CheckAnswer function returns true
So
if (CheckAnswer("What is the capital of Turkey?\n", "Ankara", score)) {
// correct. Increment score here
} else {
// incorrect. Decrement lives here
}```
I would be spamming if else for each question
bool CheckAnswer(char *Question, char *Corrects, int scored){
char Answer[100];
printf("%s", Question);
fgets(Answer, sizeof(Answer), stdin);
Answer[strcspn(Answer, "\n")] = '\0';
if(strcmp(Answer, Corrects) == 0){
puts("correct!\n");
scored++;
}
else{
puts("incorrect\n");
return false;
}
}
i added another parameter which is score
one problem is that it doesnt store all points inside of int main
your final score would be 1 always no matter how correct answers you got
You could for loop over an arrays of questions and answers
But if you want to do it this way, then you'd pass int *scored to the function
Pointers are for when the variable lives somewhere else (in this case inside of main)
lemme see
error CheckAnswer makes pointer of integer
maybe i should assign the pointer into a variable that holds the value
nope
Yes
As long as pointer is of type int *
Need to see more code if this still isn't fixed, since I can't guess what you've actually typed
Nice!
Another route you could have taken is making an array of questions and answers and using a for loop over them:
#define countof(array) (sizeof(array)/sizeof(array)[0])
const char *questions[] =
{
"What is the capital of Turkey?",
"What band produced My Little Dark Age?",
...
};
const char *answers[] =
{
"Ankara",
"MGMT",
...
};
_Static_assert(countof(questions) == countof(answers));
for (size_t i = 0; i < countof(questions); i++) {
const char *question = questions[i];
const char *answer = answers[i];
// question asking code
}```