0

I am currently learning C, and I have had this problem for some time. If it runs, it does not work how it should work, and sometimes it just does not run. It is supposed to if you give a correct answer, you get a point, but even if you get it wrong, it still says its correct and gives you a point. Anyone could help me here? Here is the code:

This works fine

char name[50], answer;
int point;
printf("Enter your name!\n");
scanf("%s", &name);
printf("\t \t \t Welcome to the game, %s! \n", name);
point = 0;
printf("\t \t \t POINTS: %d \n", point);

And here is the question and answer..does not work that well

printf("2+2? \n");
printf("a) 4 \n");
printf("b) 5 \n");
scanf("%s", &answer);
if (answer = "a") {
    printf("Correct\n");
    point++;
    printf("\t \t \t POINTS: %d \n", point);
}
else {
    printf("Not correct");
}
printf("2+3? \n");
printf("a) 5 \n");
printf("b) 4 \n");
scanf("%s", &answer);
if (answer = "a") {
    printf("Correct\n");
    point++;
    printf("\t \t \t POINTS: %d \n", point);
}
else {
    printf("Not correct");
}
Boris
  • 602
  • 2
  • 8
  • 29

1 Answers1

1

You read in answer with %s. However, it is a char. Therefore you should read in the answer using scanf("%c", &answer);.
Next thing: If you have an if-statement and you want to compare two values, you do that by using ==. Note that = is an assignment operator and assigns a value to something, in your case it assigns "a" to answerand == checks for equality.
When comparing characters, e.g. if (answer == "a") don't use " ". Those indicate a const char * that is terminated with the NULL character (\0). Instead, to check for single characters, use ' ', e.g. if (answer == 'a'.
EDIT: Instead of using

point++;
printf("\t \t \t POINTS: %d \n", point);   

you can do that in one line:

printf("\t \t \t POINTS: %d \n", ++point);

You used postfix-notation point++. That increments the variable after the command. Using ++point increments the variable in the very same command. For more check out this question about postfix/prefix, click here.

Community
  • 1
  • 1
hm1912
  • 314
  • 1
  • 10