天天看點

C程式設計——簡單實作學生資訊管理系統

作者:千裡馬的驢

下述例子主要用于展示一下結構體的使用,并非真正的管理系統,

// 定義結構體Student,表示學生資訊
struct Student {
    char name[20]; // 姓名
    int age; // 年齡
    float score; // 成績
};

#include <stdio.h>

int main() {
    // 聲明一個結構體數組,用于存儲學生資訊
    struct Student students[100];
    int count = 0; // 記錄添加的學生數量
    int choice; // 記錄使用者輸入的選項
    int i; // 循環計數器
    char name[20]; // 用于存儲要查找的學生姓名 

    // 無限循環,直到使用者輸入0退出
    while (1) {
        // 列印菜單
        printf("\n***********************************\n");
        printf("1. 添加學生資訊\n");
        printf("2. 顯示學生資訊\n");
        printf("3. 查找學生資訊\n");
        printf("0. 退出程式\n");
        printf("***********************************\n");

        // 讀取使用者輸入的選項
        printf("請輸入選項:");
        scanf("%d", &choice);

        // 根據使用者的選項執行相應的操作
        switch (choice) {
            case 1: // 添加學生資訊
                printf("請輸入學生姓名、年齡和成績:");
                scanf("%s %d %f", students[count].name, &students[count].age, &students[count].score);
                count++; // 添加完畢後數量加1
                break;
            case 2: // 顯示學生資訊
                if (count == 0) {
                    printf("沒有添加任何學生資訊!\n");
                } else {
                    printf("姓名\t年齡\t成績\n");
                    for (i = 0; i < count; i++) {
                        printf("%s\t%d\t%f\n", students[i].name, students[i].age, students[i].score);
                    }
                }
                break;
            case 3: // 查找學生資訊
                if (count == 0) {
                    printf("沒有添加任何學生資訊!\n");
                } else {
                    printf("請輸入要查找的學生姓名:");
                    scanf("%s", name);
                    for (i = 0; i < count; i++) {
                        if (strcmp(students[i].name, name) == 0) {
                            printf("該學生的姓名、年齡和成績分别為:%s、%d、%f\n", students[i].name, students[i].age, students[i].score);
                            break;
                        }
                    }
                    if (i == count) {
                        printf("沒有找到該學生的資訊!\n");
                    }
                }
                break;
            case 0: // 退出程式
                printf("程式已退出!\n");
                return 0;
            default: // 選項輸入錯誤
                printf("選項輸入錯誤,請重新輸入!\n");
                break;
        }
    }
}           

繼續閱讀