Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading In A String and comparing it C

Tags:

c

string

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 :(

like image 485
Richard Fox Avatar asked Dec 22 '22 04:12

Richard Fox


1 Answers

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.

like image 128
Brian R. Bondy Avatar answered Jan 05 '23 21:01

Brian R. Bondy