0

I am new to programming. I am trying to get result (in C) from below code but failed. I am trying to take input from user but enter into a loop if the entry is incorrect and proceed further if entry is correct.

scanf("%s",employee.gender);
do
{
    printf("Invalid entry");
    printf("\nEnter Employee's Gender (Male/Female): ");
    scanf("%s",employee.gender);
}
while (employee.gender != "Male");
Sanna
  • 1
  • 1
  • Also, your loop will *always* get entered because it is a do...while loop. Maybe you want to use a regular `while` loop. – David Grayson Sep 03 '22 at 01:38
  • You can't compare strings in C like that. Look up the standard library function strcmp(). Also, do-while loops execute at least once. Perhaps a while loop instead that has the test at the top of the loop? – Avi Berger Sep 03 '22 at 01:40
  • `employee.gender != "Male"` is incorrect. Use `memcmp(employee.gender, "Male", 5)` instead. – user16217248 Sep 03 '22 at 01:41
  • @DavidGrayson: I'm not sure if that question is a good duplicate target, because that question has a serious unrelated issue: It makes use of `gets` in several places. However, apart from that issue, it is a perfect duplicate target. – Andreas Wenzel Sep 03 '22 at 01:59

1 Answers1

1

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);
mikyll98
  • 1,195
  • 3
  • 8
  • 29