Search code examples
cstrncmp

strncmp doesn't return 0 on equal strings


Shouldn't the strncmp("end",input,3) == 0 return 0 if the input is end? It returns a number > 0 though.

#include <stdio.h>

int main(void) {
  char *strArray[100];
  int strLengths[100];
  char input[100];
  int flag = 0;
  do {
    scanf("%c",&input);
      if(strncmp("end",input,3) == 0) {
        printf("end\n");
      }
      printf("%d\n",strncmp("end",input,3));
    } while(flag !=0);
  return 0;
}

Solution

  • This

    scanf("%c",&input);
    

    reads just a single char - maybe. It's wrong - pay attention to the errors and warnings you get from your compiler.

    The format specifier is not correct - %c means scanf() will attempt to read a char, but you're passing the address of a char[100] array. That's undefined behavior, so anything might happen.

    You're also not checking the return value to see if scanf() worked at all, so you don't really know what's in input.