Search code examples
cstrcmp

Comparing user input to a predefined array of characters in C programming language


I have the following code which is supposed to get user input as commands then check whether the command is predefined. However, for any command entered the output is "You asked for help". I figured that the problem might be related to the way I'm comparing the user input string with the set string(s) but I still need help solving the problem.

char command[10];
char set[10];
char set1[10];
strcpy(set, "help");
strcpy(set1, "thanks");

int a = 0;
while (a != 1)//the program should not terminate.
{
   printf("Type command: ")
   scanf("%s", command);
   if (strcmp(set, command))
   {
       printf("You asked for help");
   }
    else if (strcmp(set1, command))
   {
       printf("You said thanks!");
   }
   else
   {
       printf("use either help or thanks command");
   }
}

Solution

  • if (strcmp(set, command))
    

    should be

    if (strcmp(set, command) == 0)
    

    The reason is that strcmp returns a nonzero value if the LHS or RHS is larger, and zero if they are equal. Since zero evaluates to "false" in a conditional, you'll have to explicitly add the == 0 test to make it true in the sense that you're expecting, which is equality.