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:
strcmpwill 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.Why your program crashes:
Another problem is that
inputshould be a char buffer. Like so:char input[1024];Currently you have
inputas a pointer to a null terminated string (which is read only memory)Friendly suggestion:
Also don’t put the null terminated
\0inside the string literals. It is implied automatically when you use a string literal. It doesn’t matter to double null terminate as far asstrcmpis concerned, but it may cause problems elsewhere in your future programs. And people will wonder why you’re doing double null termination.