1

Im trying to write a program that will search a surname in database of students and print whole line where that surname is. Every time I run it, it says No Match.

void search(){
 FILE *file;

file = fopen("students.txt", "r");
char sSurrname[100];

char id[10];
char name[10];
char the_name[100];
char surrname[10];
char phone[10];
char the_surrname[100];
char phone_number[100];
int the_id;

printf("Type searched surrname: ");
scanf("%s", &sSurrname);
while (!feof(file)){
fscanf(file, "%s %d || %s %s || %s %s || %s %s ||", &id, &the_id, &name, &the_name, &surrname, &the_surrname, &phone, &phone_number);

if (strcmp(sSurrname, the_surrname) == 0) {
  printf("%s %d || %s %s || %s %s || %s %s ||", &id, &the_id, &name, &the_name, &surrname, &the_surrname, &phone, &phone_number);
  break;
} else {
  printf("No Match.");
  break;
  continue;
}

This is the database:

ID: 0 || Name: Pepa || Surrname: Hnatek || Phone: 321 ||

ID: 1 || Name: Jan || Surrname: Novak || Phone: 123 ||

nero
  • 33
  • 3
  • What is `vyhJm` that’s being compared to? I don’t see it defined – Sami Kuhmonen Dec 07 '19 at 13:11
  • 1
    Putting `&` before character arrays to use in `scanf()` and `printf()` is wrong. Your usage of `while (!feof(file))` is also [wrong](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – MikeCAT Dec 07 '19 at 13:13
  • 1
    Not only `vyhJm` but also `rodne` seems undefined. Please post a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – MikeCAT Dec 07 '19 at 13:15
  • Sorry, I was translating the code into eng. vyhJm = sSurrname and rodne = the_surrname – nero Dec 07 '19 at 14:55
  • 1
    Also remove the `break` statement from the `else` block, otherwise the search will apply just to the first line. – lainatnavi Dec 07 '19 at 15:25
  • Declare phone_number as int, adjust the fscanf like this `fscanf(file, "%s %d || %s %s || %s %s || %s %s ||", id, &the_id, name, the_name, surrname, the_surrname, phone, &phone_number);` and the `printf`.... Remove the second `break`. Like this it should work. – lainatnavi Dec 07 '19 at 18:02
  • Removed second break, made phone_number int, still not working. Now it just prints No match 3 times. – nero Dec 07 '19 at 23:49

0 Answers0