I am new to C and am still a bit confused about how to use strings via character arrays.
In my C program, I am accepting commands from the user:
char command[20];
scanf("%s",command);
Of course, afterwards I want to figure out what command they typed (something similar to: "if (command == "hello")
, then do something"). I know this is not possible in C because I am comparing a string literal to a character array, but what would be a good way to it? I have tried using strcmp(command, "hello")
and still got errors.
Any advice you can provide would be very appreciated. Thank you!
I have written a complete version of what I think you are trying to do:
#include <string.h>
void main()
{
char command[20];
scanf("%s",command);
// command and "hello" can be less than, equal or greater than!
// thus, strcmp return 3 possible values
if (strcmp(command, "hello") == 0)
{
printf("\nThe user said hello!");
}
}
Several people have commented about using scanf
and they are correct, except that a new programmer has to start somewhere in learning this stuff, so don't feel too bad we are all learning...
Hope this helps.