可能有點過了頂你想要的東西,但誰的票:
#include <stdio.h>
#include <string.h>
struct student {
int id;
char name[50];
int age;
char dept[10];
float grade;
};
void print_student(struct student * students, size_t num_students, int id);
void set_student_by_id(struct student * students, size_t num_students,
int id, struct student * new_info);
int main(void) {
struct student students[5] = {
{100, "John", 17, "Physics", 3.2},
{101, "Emily", 16, "Maths", 3.8},
{102, "Peter", 18, "Drama", 2.1},
{103, "Doug", 16, "English", 3.3},
{104, "Sara", 17, "Astronaut", 3.9}
};
size_t num_students = sizeof(students)/sizeof(students[0]);
/* Print details for student 101 before change */
print_student(students, num_students, 101);
/* Change details for student 101 */
struct student new_info = {-1, "Emily", 17, "Farming", 3.9};
set_student_by_id(students, num_students, 101, &new_info);
/* Print details for student 101 after change */
print_student(students, num_students, 101);
/* Attempt to print details for imaginary student 105 */
print_student(students, num_students, 105);
return 0;
}
/*
* Prints the details for a selected student.
*
* Arguments:
* students - pointer to an array of students
* num_students - number of students in the array
* id - ID of the student to print
*/
void print_student(struct student * students, size_t num_students, int id) {
size_t i;
for (i = 0; i < num_students; ++i) {
/* Search array for student by ID */
if (students[i].id == id) {
printf("Info for student ID %d:\n", id);
printf(" Name: %s\n", students[i].name);
printf(" Age: %d\n", students[i].age);
printf(" Dept: %s\n", students[i].dept);
printf(" Grade: %.1f\n", students[i].grade);
break;
}
}
if (i == num_students) {
printf("Student ID %d not found.\n", id);
}
}
/*
* Changes the details for a selected student.
*
* Arguments:
* students - pointer to an array of students
* num_students - number of students in the array
* id - ID of the student to change
* new_info - pointer to struct student containing new details
*/
void set_student_by_id(struct student * students, size_t num_students,
int id, struct student * new_info) {
size_t i;
for (i = 0; i < num_students; ++i) {
/* Search array for student by ID */
if (students[i].id == id) {
/* Change everything except the ID */
strcpy(students[i].name, new_info->name);
strcpy(students[i].dept, new_info->dept);
students[i].age = new_info->age;
students[i].grade = new_info->grade;
break;
}
}
if (i == num_students) {
printf("Student ID %d not found.\n", id);
}
}
輸出:
[email protected]:~/src/c/scratch$ ./student
Info for student ID 101:
Name: Emily
Age: 16
Dept: Maths
Grade: 3.8
Info for student ID 101:
Name: Emily
Age: 17
Dept: Farming
Grade: 3.9
Student ID 105 not found.
[email protected]:~/src/c/scratch$
那你試試? 我的建議是,如果你想修改3號學生的信息,你可以通過s [2] .id = 5,s [2] .name =等來做到這一點。 –
lightbringer
結果是什麼,你期望什麼作爲結果?我的意思是你寫了一些很好的代碼。問題究竟在哪裏開始? –
@DanielS。例如輸入學生信息後,您可以選擇一個學生,並更改名稱或等級 –