Reputation: 61
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");
}
}
Upvotes: 3
Views: 509
Reputation: 134396
First of all, always length-bound your input while using scanf()
, like
scanf("%9s", command);
for a 10-element char
array, to avoid buffer overflow by overly-long inputs.
That said, the if...else
block logic works in below way:
if (expression is true) { // produce a non-zero value, truthy
execute the if block
}
else { // expression is falsy
execute the else block
}
In your case, the controlling expression is strcmp(set, command)
.
Now, point to note, in case of a match, strcmp()
returns a 0
, in case of mismatch, it returns a non-zero value.
Thus,
0
- which will be evaluated as falsy and against your expectation, it'll go to the else
part.if
block will be executed erroneously.So, in your case, you need to change the condition to negate the return value, like
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");
}
Upvotes: 2
Reputation: 57289
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.
Upvotes: 8