Reputation: 13
Hi my program basically is when a user input an unrecognizable command it suppose to display an error message, however when the user input valid commands and non valid commands it still displays error message.
int main(){
char command[20];
printf("Enter either add, sub, mult, div, or EXIT:\n");
scanf("%5s", command);
if(strcmp(command, "EXIT") || strcmp(command, "add" ) ||strcmp(command, "sub")|| strcmp(command,"div") || strcmp(command,"mult") != 0){
printf("Warning either enter the following commands\n");
}
else
{
printf("Welcome\n");
//function..
}
return 0;
}
Also i am new to C and i am experimenting i'm not sure if that is the proper way to implement this feature.
Upvotes: 1
Views: 88
Reputation: 896
The strcmp
function returns 0
if the two strings match. Consequently your condition will always evaluate as true
, since only one string can match with a certain input.
Upvotes: 0
Reputation: 64730
By doing:
if (strcmp || strcmp || strcmp || strcmp != 0)
You seem to be trying to check ALL the different results against 0 at the same time.
That is not how C works.
You must check each value individually
if (strcmp(command, "EXIT") &&
strcmp(command, "add" ) &&
strcmp(command, "sub" ) &&
strcmp(command, "div" ) &&
strcmp(command, "mult"))
{ /* Show Warning message */ }
Translation:
If the string is not "EXIT"
and also is not "add"
, and also is not "sub"
.... then the string was not any known command; Therefore, show a warning.
Upvotes: 4