To compare "strings" in C you need to use strcmp()
, a function defined in string.h
header, which takes 2 arguments string1
and string2
and compares them, returning:
- 0 if they're equal;
- -1 if
string1
precedes alphabetically string2
;
- 1 otherwise.
I've put it in quotes because C language doesn't have a proper string abstraction. Instead, strings are represented as an array of char values: char str[MAX_STR_LENGTH];
. In order to use strcmp()
function you need to include the header where it's declared, so you need to insert #include <string.h>
at the top of your file.
The reason why you cannot use the ==
operator, is because when you try to compare 2 arrays that way you're actually comparing the two arrays' memory addresses, which are obviously different for different arrays.
Instead, strcmp()
function loops over both of the arrays and checks for differences between their elements, one character by one.
Further considerations
Your code presents some conceptual mistakes:
- you're reading the input 2 times before checking the while condition;
- for each loop cycle you're printing the error message before checking the condition.
A better solution would be the following:
do
{
printf("Enter Employee's Gender (Male/Female)");
scanf("%s", employee.gender);
if (strcmp(employee.gender, "Male") != 0 && strcmp(employee.gender, "Female") != 0)
{
printf("Invalid entry\n");
}
} while (strcmp(employee.gender, "Male") != 0 && strcmp(employee.gender, "Female") != 0);