The requirements:
Write a C program that executes the following tasks in order:
- Initially displays the content of the file in the execution window
- Ask the user for an ID, search for the ID in the file then display a message (in the execution window) in the following format: Student with ID:……… corresponds to ………………. who is majoring in……………… As you print the name of the student in the output, do not print ‘_’!
The problem: It only outputs the first line (aka first student info) from the file, and it does not even ask for the student ID afterward.
The code:
#include <stdio.h>
#include <string.h>
typedef struct {
int ID;
char Last_name[30], First_name[30], major[30];
} Class;
int search_for_student(int ID_to_search, Class students[22]) {
int i;
for (i = 0; i < 22; i++) {
if (students[i].ID == ID_to_search)
return i;
}
return -101;
}
void main(void) {
char line[100];
int ID_to_search, i, index, j;
Class students[22];
FILE* infp;
infp = fopen("Section_06.txt", "r");
if (infp == NULL) {
printf("File unexistant!\n");
}
else {
for (i = 0; i < 22; i++) {
fscanf(infp, "%d", students[i].ID);
printf("%d", students[i].ID);
fscanf(infp, "%s", students[i].Last_name);
for (j = 0; j < strlen(students[i].Last_name); j++) {
if (students[i].Last_name[j] == '_')
students[i].Last_name[j] = ' ';
}
printf("%s", students[i].Last_name);
fscanf(infp, "%s", students[i].First_name);
for (j = 0; j < strlen(students[i].First_name); j++) {
if (students[i].First_name[j] == '_')
students[i].First_name[j] = ' ';
}
printf("%s", students[i].First_name);
fgets(students[i].major, 30, infp);
printf("%s", students[i].major);
}
printf("Enter an ID: ");
scanf("%d", &ID_to_search);
index = search_for_student(ID_to_search, students);
if (index == -101)
printf("Student not found!");
else {
printf("Student with ID: %d corresponds to %s %s who is majoring in %s.", students[index].ID, students[index].First_name, students[index].Last_name, students[index].major);
}
}
fclose(infp);
}