fgets() includes the newline at the end

Man Person picture Man Person · Nov 18, 2012 · Viewed 42.9k times · Source
fgets(input,sizeof(input),stdin);
if (strcmp(input, "quit") == 0){
  exit(-1);
}

If I type quit, it does not exit the program; I'm wondering why this is the case.

By the way input is declared as char *input;.

Answer

codaddict picture codaddict · Nov 18, 2012

The function fgets might add a newline at the end of the string read. You'll have to check that:

size_t ln = strlen(input) - 1;
if (input[ln] == '\n')
    input[ln] = '\0';

or even

strtok(input, "\n");