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.

4
  • 2
    Have you tried printing your input variable first? Commented Mar 29, 2016 at 17:55
  • @cad space for null character... Commented Mar 29, 2016 at 18:05
  • Googling your exact title gives: 'About 60,500 results', with three SO Q&A about the 'newline' issue as the first three entries. Commented Mar 29, 2016 at 18:08
  • 4
    @Muzahir Hussain: Firstly, why would you reserve two bytes for one null character? Secondly, fgets already knows to reserve space for null character internally. Commented Mar 29, 2016 at 18:19

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

8 Comments

This method will break if the last line of a file does not have newline, or if the input buffer passed to fgets was shorter than the text line length.
Yes, but, alk and vlad have a better way.
@WeatherVane ...which I wholeheartedly agree with. :-)
Yes, fgets can append a newline character. But using strchr to search for it is an atrocity.
@AnT How is it an "atrocity"?
|
4

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

strcmp(input, "exit\n") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.