1
#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.

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
Muzahir Hussain
  • 1,009
  • 2
  • 16
  • 35

4 Answers4

8

You get 10 because there is a newline character in your input string. the 10 return value is the difference between the ascii value of that newline character and the terminating null character of the "exit" string literal you're comparing to.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
6

Function fgets also includes the new line character '\n' that corresponds for example to the pressed Enter key if there is enough space in the array.

You should remove it for example the following way

fgets( input, SIZE, stdin );
input[strcspn( input, "\n" )] = '\0';

or more safe

if ( fgets( input, SIZE, stdin ) != NULL ) input[strcspn( input, "\n" )] = '\0';

Take into account that this code

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

in general is invalid because the new line character can be absent in the array and the function strchr will return NULL.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
5

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).

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
4

fgets() keeps the '\n'. You either remove it from input (see other answers) or add it to the literal

strcmp(input, "exit\n")
pmg
  • 106,608
  • 13
  • 126
  • 198