I've been trying to come up with a system that searches through a file line by line for a 6 digit number and when it finds it it breaks the loop and outputs the line it found but for some reason whenever I run my attempt the program just exits. Any help would be appreciated
searching = 1;
while (searching == 1) {
search = 0;
printf("Please enter the UP number of the student:\n");
scanf(" %d", &w);
while (search != 1) {
fgets(line, 60, StudentDB);
t = strstr(line, w);
if (t != NULL && t != -1) {
search = 1;
printf("The student's data is:\n");
printf("%s\n", line);
printf("What would you like to do now\n1. Edit marks\n2. Delete record\n3. Search for a different record\n4. Return to menu\n");
scanf(" %d", &v);
switch (v)
case 1:
case 2:
case 3:
break;
case 4:
;
break;
}
if (line == EOF) {
search = 1;
printf("There is no student with that UP number saved.\nWhat would you like to do?\n");
printf("1. Search for a different number\n2. Return to the menu\n");
scanf(" %d", &v);
switch (v) {
case 1:
break;
case 2:
searching = 0;
search = 1;
break;
}
} else {
printf("Something went horribly horribly wrong");
}
break;
}
}
You cannot search for a number with t = strstr(line, w);
The second argument to strstr
must be a string. You should define w
as a char w[7];
, read the 6 digit number as a string with scanf("%6s", w)
and use strstr(line, w)
to find the number in the line.
Note also that t != -1
makes no sense, t
should be a char *
, which will be either NULL
if the number is not present or a valid pointer into the line if strstr
found the number on it.
Similarly, it makes no sense to test for end of file after searching the line: at the end of file, fgets()
returns NULL
and the line was not read.