简体   繁体   中英

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;
}

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 .

In your case, the strings compared with strncmp("end",input,3) == 0 will never match as input will contains only one character.

The call scanf("%c",&input); will read only the 1st character entered, and will store it in input

#include <stdio.h>

int main(void) {
  char *strArray[100];
  int strLengths[100];
  char input[100];
  int flag = 0;
  do {
    scanf("%s",input);  //%c is for a single char and %s is for strings.
      if(strncmp("end",input,3) == 0) {
        printf("end\n");
      }
      printf("%d\n",strncmp("end",input,3));
    } while(flag !=0);
  return 0;
}

Next time print the input before continuing to confirm that you are doing it correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM