Reputation: 59
I am new to coding in C and trying to write a program that prints the message 'You may enter' if your age is 15 or over, and your gender is equal to male. Kindly see what I've got below. When you enter your age as 15 or over and your gender as male, the program prints the wrong message. I think it could be a problem with my logical operators but I can't quite figure out why. Could you assist?
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int age;
char gen;
printf("How old are you?\n");
scanf("%d", &age);
printf("What is your gender? (m/f) \n");
scanf("%s", &gen);
if(age >= 15 && gen == 'm')
{
write(1, "You man enter\n", 15);
}
if(age < 14 || gen == 'f')
{
write(1, "No entry\n", 9);
}
return 0;
}
Upvotes: 1
Views: 98
Reputation: 59
Thanks @gsamaras!
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int age;
char gen;
printf("How old are you?\n");
scanf("%d", &age);
printf("What is your gender? (m/f) \n");
scanf(" %c", &gen);
if(age >= 15 && gen == 'm')
{
write(1, "You may enter\n", 15);
}
if(age <= 14 || gen == 'f')
{
write(1, "No entry\n", 9);
}
return 0;
}
Upvotes: 1
Reputation: 73444
Change this:
scanf("%s", &gen);
to this:
scanf(" %c", &gen);
since gen
is a character, not a string.
Note the space I left before the format specifier for characters, which is there to inform the method to automatically eat whitespaces and special characters (remove it and see what happens). For more, ready my initial reaction to this Caution when reading char with scanf (C).
Upvotes: 3