Search code examples
cstrcmp

C - Strcmp() not working


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{

const int SIZE = 100;

char input[SIZE];

while(1)
{
    fgets (input, SIZE - 2, stdin);          // input
    printf("%d", strcmp(input, "exit"));    //returining 10 instead of 0

    if(strcmp(input, "exit") == 0)
    {
        printf("SHELL Terminated\n");
        exit(0);    
    }

return 0;
}

I am facing a problem. If I enter exit in input variable, the function strcmp() returns 10, but it should return 0 and exit the program as exit is equal to exit. But it does not.

I can't find the problem.


Solution

  • fgets appends a newline (\n) character to the end of the string read into the buffer.

    Delete it using

    char* newline = strchr(input, '\n');
    if (newline)
        *newline = '\0';
    

    As @WeatherVane mentioned, some calls of fgets might not set a newline in the buffer, so we need to check if strchr returns NULL (no newline found).