-3

I've started learning C programming language recently. I wanted to write a simple yes/no program, however, there is an error in my code that I cannot seem to find a solution to.

Here is the code:

#include <stdio.h>

int main()
{
char answer[10];


printf("do you like programming? yes/no\n");
scanf(" %s", &answer);

if((answer == 'yes')|| (answer == 'no')){
    printf("you are awesome\n");
}
else{
    printf("try again\n");
}
return 0;
}

When I use y/n instead of yes/no, the program works fine. I know that I need to replace char with string, but I do not know how to do that. I read somewhere that I need to use a function called strcmp, but I do not know how to use that either. If anyone could help me, I would be really grateful.

Thanks in advance!

crossdeath
  • 95
  • 1
  • 7

1 Answers1

0

When you type if((answer == 'yes')|| (answer == 'no')), the == operator in this case is not comparing the strings, but instead the pointers to the strings. To test equality of the strings, use strcmp. Your if statement would then look this this:

#include <string.h>

...

if(strcmp(answer, "yes") == 0 || strcmp(answer, "no") == 0) {

...
Jerfov2
  • 5,264
  • 5
  • 30
  • 52