0

Here is my code:

  printf("Please input a command\n");

  char *input;
  input = malloc(sizeof(char) * 50);

  if(fgets(input, 50, stdin) != NULL) {
    if(strcmp(input, "end\0") == 0) {
      printf("END");
    }
  }

For some reason when I input 'end', it doesn't print "END". What is the problem here that is causing the loop condition to fail? strcmp(input, "end\0") == 0 Should return 0 when the input pointer is equal to "end\0"? I've also tried strcmp(input, "end") == 0 and this doesn't work either. How can I fix this?

klutt
  • 30,332
  • 17
  • 55
  • 95
andydydyy
  • 13
  • 2

2 Answers2

1

fgets includes the newline. Use strcmp(input, "end\n")

From the documentation:

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

And as mentioned in comments, you do not need to include \0 when using string literals. The nulltermination will be added automatically.

Community
  • 1
  • 1
klutt
  • 30,332
  • 17
  • 55
  • 95
0

You could strip newline characters \r and \n before comparing the string:

int length = strlen(input);

if(length>0 && input[length-1]=='\n') {
    input[length-1]='\0';
    length--;
}
if(length>0 && input[length-1]=='\r') {
    input[length-1]='\0';
    length--;
}

This code should be universal for windows linux and mac. Next, I've used unsafe functions like strlen and strcmp in my example, there's also strncmp that compares only specified number of bytes.

nio
  • 5,141
  • 2
  • 24
  • 35
  • 1
    The idea is good, but you can do the same with `size_t length = strcspn(input, "\r\n"); input[length] = '\0';`. – Bob__ Dec 17 '17 at 17:47