-4

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;
}
schnaader
  • 49,103
  • 10
  • 104
  • 136
Stelios Papamichail
  • 955
  • 2
  • 19
  • 57

3 Answers3

3

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.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56
0

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

CimCim
  • 48
  • 5
-1
#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.

Capie
  • 976
  • 1
  • 8
  • 20