Pyrromanis Pyrromanis - 1 month ago 17
C Question

C-fgets() using stdin doesnt work

I'm trying to get input from

stdin
using
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
}

Answer

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.