c语言 实现从文本中读取出指定学号的学生信息并显示,文本文件存放格式是每一行对应一个学生信息,最后一行没有换行符
时间: 2024-01-01 17:23:20 浏览: 90
以下是使用C语言实现从文本中读取出指定学号的学生信息并显示的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGTH 100
typedef struct {
char name[MAX_LENGTH];
int age;
int studentID;
float averageScore;
} Student;
void readStudentInfoFromFile(const char* filename, Student* students, int* numStudents) {
FILE* file = fopen(filename, "r");
if (file == NULL) {
printf("Failed to open the file.\n");
return;
}
char line[MAX_LENGTH];
*numStudents = 0;
while (fgets(line, sizeof(line), file)) {
sscanf(line, "%s %d %d %f", students[*numStudents].name, &students[*numStudents].age, &students[*numStudents].studentID, &students[*numStudents].averageScore);
(*numStudents)++;
}
fclose(file);
}
void displayStudentInfo(const Student* students, int numStudents, int studentID) {
int i;
for (i = 0; i < numStudents; i++) {
if (students[i].studentID == studentID) {
printf("Name: %s\n", students[i].name);
printf("Age: %d\n", students[i].age);
printf("Student ID: %d\n", students[i].studentID);
printf("Average Score: %.2f\n", students[i].averageScore);
return;
}
}
printf("Student with ID %d not found.\n", studentID);
}
int main() {
const char* filename = "student_info.txt";
Student students[MAX_LENGTH];
int numStudents;
readStudentInfoFromFile(filename, students, &numStudents);
int studentID;
printf("Enter the student ID: ");
scanf("%d", &studentID);
displayStudentInfo(students, numStudents, studentID);
return 0;
}
```
阅读全文