-2

I have to compare 2 strings, one from a file, and one from a user input, here is the file:

Password 
abcdefg 
Star_wars 
jedi
Weapon 
Planet 
long 
nail 
car 
fast 
cover 
machine 
My_little
Alone
Love
Ghast

The code for getting the string from the line is fine but the code for comparing the 2 strings does not give the right output

int main(void){
  int loop, line;
  char str[512];
  char string[512];
  FILE *fd = fopen("Student Passwords.txt", "r");
  if (fd == NULL) {
    printf("Failed to open file\n");
    return -1;
  }
  printf("Enter the string: ");
  scanf("%s",string);
  printf("Enter the line number to read : ");
  scanf("%d", &line);

  for(loop = 0;loop<line;++loop){
    fgets(str, sizeof(str), fd);
  }
  printf("\nLine %d: %s\n", line, str);

  if(strcmp(string,str) == 0 ){
    printf("Match");
  }else{
    printf("No Match");
  }
  fclose(fd);
  getch();
  return 0;
}

Perhaps the str resets but i don't know, perhaps some of the talented programmers here can see the problem.

Anyone know what is wrong with my string comparison?

Correct output: Input: jedi, 4 Output: Match

edit: Both strings are the same, in the same case edit: dreamlax fixed this.

17
  • what do mean by adding a structure tag??
    – vinayawsm
    Jan 29, 2014 at 12:26
  • 1
    so, you mean, that str is jedi and string is Jedi? And the strcmp "fails"? Jan 29, 2014 at 12:26
  • @invalid_id Maybe, Does it matter? Jan 29, 2014 at 12:26
  • 2
    strcmp() compares strings case-sensitively, meaning Jedi and jedi are considered different. You need to use strcasecmp() if you want to compare strings disregarding case.
    – dreamlax
    Jan 29, 2014 at 12:27
  • 1
    @user3227362 - stop vandalising your questions by completely changing the question. You're well on your way to an automated question ban if you keep this up. Jan 30, 2014 at 13:16

1 Answer 1

6

fgets() does not discard any newline character after reading, so it will be part of str, which will cause the comparison to fail since string won't have a newline character. To get around this, you simply need to remove the newline character from str.

str[strlen(str) - 1] = '\0';
if (strcmp(string, str) == 0)
    // ...

Ideally, make sure strlen(str) > 0 first, otherwise you will invoke undefined behaviour.

2
  • Thank you, this works, the output is correct, when 6 minutes pass i'll happily accept the answer Jan 29, 2014 at 12:31
  • @user3227362: No worries, this particular property of fgets has tripped me up before.
    – dreamlax
    Jan 29, 2014 at 12:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.