Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top