0

I am trying to make a quiz program that reads questions from one file and answers from another file, put them in strings and compare them with strcmp(), but for some reason its not working when I put in a correct answer it says its not correct. Any help would be appreciated.

My Code

int main()
{

    FILE *fpq = fopen("questions.txt", "r");
    FILE *fpa = fopen("answers.txt", "r");

    char question[256];
    char answer[256];
    char user_input[256];

    fgets(question, 256, fpq);
    fgets(answer, 256, fpa);

    puts(question);
    fgets(user_input, 256, stdin);
    if(strcmp(user_input, answer) == 0)
    {
      printf("Good job!\n");
    }
    else
    {
      printf("Nope its:\n");
      puts(answer);
    }
    fclose(fpq);
    fclose(fpa);
    return 0;
}
Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
emp
  • 11

2 Answers2

1

fgets() appends a newline \n character to the end of the string read into the buffer.
Refer to this answer which will further explain it Is trailing newline necessary in fgets?

Maybe This is the reason your code is not working, please check for the new line at the end of string and remove it.

On Removing newline \n character you can refer to Removing trailing newline character from fgets() input.

Also This Question Deals With The Same Issues As Yours strcmp not working. It would be good help to you.

And As Paul Oglive Said in the comment learn to use debugger, it will always help.

Community
  • 1
  • 1
Suraj Jain
  • 4,463
  • 28
  • 39
  • Ok I will look up how to use a debugger, thanks for your advice. – emp Feb 18 '17 at 12:13
  • Does The Answer Work For You? – Suraj Jain Feb 18 '17 at 13:40
  • @emp Also Must see the above mentioned questions and answer, it will really help you a lot, and get a good book like [C Programming a modern approach By K.N King 2nd Edition](https://www.amazon.com/C-Programming-Modern-Approach-2nd/dp/0393979504/). – Suraj Jain Feb 18 '17 at 13:48
  • @emp See The Updated Answer and visit this http://stackoverflow.com/questions/967745/strcmp-not-working?rq=1 – Suraj Jain Feb 18 '17 at 17:39
-1

You can make use of strncmp to solve your problem. You need to provide the number of characters to be compared.

if(strncmp(user_input, answer, strlen(user_input) == 0)
{
  printf("Good job!\n");
}
else
{
  printf("Nope its:\n");
  puts(answer);
} 

See-example-here

Rishi
  • 1,387
  • 10
  • 14