Pyrromanis
Pyrromanis

Reputation: 45

C-fgets() using stdin doesnt work

I'm trying to get input from stdinusing fgets utilizing a character array with a size of 128 that is supposed to stop when it reads "exit" but it doesn't

char cmd[128];

if(fgets(cmd,128,stdin)=="exit"){
    //stuff
   }

Upvotes: 0

Views: 364

Answers (1)

dbush
dbush

Reputation: 223689

You can't compare strings with the == operator.

What you're actually doing here is comparing the function's return value (the address of cmd on success, NULL on failure) with the address of the string literal "exit". This will never be true.

You should check the return value for NULL, then use the strcmp function to compare cmd against "exit":

if ((fgets(cmd,128,stdin)) != NULL && 
    (strcmp(cmd,"exit\n") == 0 || strcmp(cmd,"exit\r\n") == 0) {
    ...

Note that the fgets function stores a newline in the buffer if one is read, so we need to add that to the string to check.

Upvotes: 3

Related Questions