jeudi 4 novembre 2021

I have some doubts regarding my if condition

I'm just a noob/newbie in the C/programming world. I'll first post the code and then I'll describe my problem.

#include <stdio.h>
#include <string.h>

int
main ()
{
  char f[30], j[30] = "mount everest";
  int s,a=0;
  printf ("\n");
  printf ("2) Which is the tallest mountain in the world?\n");
  printf ("\n");
  printf ("Please type your answer below\n");
  scanf("%[a-z]s",f);
  s = strcmp (f, j);
  printf ("\n");
 
  if (s == 0)
    {
      printf ("Congratulations! You have recieved a point!\n");
      a++;
    }
  else
    {
      printf ("Sorry! Better luck next time!");
      a--;
    }
  
  return 0;
}

So when I try to type the answer as "mount everest", the output goes directly to my 'else'(Sorry! Better luck next time!) statement. Also, I want the program to only accept small letters(as I've defined it a strict rule to be followed throughout the quiz).

**OUTPUT** 

2) Which is the tallest mountain in the world?

Please type your answer below
mount everest

Sorry! Better luck next time!

But when I use (not)'!s' instead of 's' in my if condition, it fulfills the if condition and prints the message as 'Congratulations! You have recieved a point!'. I really don't know what is going on? I had the same approach for my other 2 questions and they all worked perfectly without this '!' issue.

#include <stdio.h>
#include <string.h>

int
main ()
{
  char f[30], j[30] = "mount everest";
  int s,a=0;
  printf ("\n");
  printf ("2) Which is the tallest mountain in the world?\n");
  printf ("\n");
  printf ("Please type your answer below\n");
  scanf("%[a-z]s",f);
  s = strcmp (f, j);
  printf ("\n");
 
  if (!s == 0)
    {
      printf ("Congratulations! You have recieved a point!\n");
      a++;
    }
  else
    {
      printf ("Sorry! Better luck next time!");
      a--;
    }
  
  return 0;
}
**OUTPUT**

2) Which is the tallest mountain in the world?

Please type your answer below
mount everest

Congratulations! You have recieved a point!

So someone can please explain this to me of what is happening(as I'm new so I kinda don't know how to understand debugging) and what am I doing wrong here? Also, if you cannot understand from this section of the code, I'll post the whole code here but for now I thought it would be too overwhelming so if u want then pleasedo let me know! Thank you for taking the time to go through my problem. Any help is very much appreciated.

Aucun commentaire:

Enregistrer un commentaire