Im trying to create a C based string menu where a user inputs a command and then a block of code runs.
Whatever i do the conditional is never true:
char *input= "";
fgets(input, 50, stdin);
printf("%s",input);
printf("%d",strcmp( input,"arrive\0"));
if(strcmp( input,"arrive\0")==0){....
Im fairly new to c and am finding strings really annoying.
What am i doing wrong?
Note: current code crashes my program :(
Why strcmp always return non 0:
strcmp
will return 0 only when the strings are identical. As for why it's evaluating to different always. It is because fgets puts a newline character at the end of your input buffer before the null termination.
/*Will print 0 if you type in arrive<enter>*/
printf("%d",strcmp( input,"arrive\n"));
Why your program crashes:
Another problem is that input
should be a char buffer. Like so: char input[1024];
Currently you have input
as a pointer to a null terminated string (which is read only memory)
Friendly suggestion:
Also don't put the null terminated \0
inside the string literals. It is implied automatically when you use a string literal. It doesn't matter to double null terminate as far as strcmp
is concerned, but it may cause problems elsewhere in your future programs. And people will wonder why you're doing double null termination.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With