0

I'm trying compare two strings with the function srtcmp but do not get the result i want. The program is coded in C and should print the name of the user only if is older and male. Any case, only else instructions are executed.

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

int main() {

char name[20], sex[15];
int age;

printf("\n Your name here: "); fgets(name, 21, stdin);
printf(" Your sex here: "); fgets(sex, 16, stdin);
printf(" You age here: "); scanf("%i", &age);

if(strcmp(sex, "male")==0 && age>=18) {
    printf("\n %s you are old.\n\n", name);     
}

else {
    printf("\n You are not old.\n\n");
}

return 0;
}
Jose
  • 1
  • 1
  • 4
    You say you're not getting the result you want, but you haven't specified what inputs you're giving to your program and what it actually outputs. Note that `fgets` normally includes a trailing newline from the input. Also, you're lying to `fgets` about how big your buffers are. It's fine to tell give `fgets` buffer sizes smaller than they actually are, but you're doing the opposite. – jamesdlin Sep 01 '16 at 03:41
  • I'd suggest you perform some basic debugging by printing out the `name` to see what it is. – Dat Nguyen Sep 01 '16 at 03:42
  • 1
    `fgets()` keeps a newline at the end of the data it reads; your string `"male"` does not have a newline at the end. So, the strings never compare equal. – Jonathan Leffler Sep 01 '16 at 03:42

0 Answers0