首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

字串轉整數與結構體陣列排序綜合實例

     編輯:關於C語言

需求場景

從檔案讀取學生資料 (學號字串、姓名、性別),將學號轉為整數進行排序,支援查詢與列印功能。

核心資料結構

#define MAX_STUDENTS 100

typedef struct {
    char name[32];
    char id_str[16];   // 學號字串 (如 "2023001")
    int id_num;        // 轉換後整數
    char gender;       // 'M'/'F'
} Student;

Student students[MAX_STUDENTS];
int count = 0;

關鍵功能實現

1. 字串轉整數 (atoi/strtol)

// 簡易版
int id = atoi(student.id_str);

// 健壯版 (支援錯誤檢查)
char *endptr;
long id = strtol(student.id_str, &endptr, 10);
if (*endptr != '\0') { /* 格式錯誤處理 */ }

2. 檔案讀取與轉換

void load_data(const char *filename) {
    FILE *fp = fopen(filename, "r");
    if (!fp) return;
    
    while (count < MAX_STUDENTS && 
           fscanf(fp, "%31s %15s %c", 
                  students[count].name,
                  students[count].id_str,
                  &students[count].gender) == 3) {
        students[count].id_num = atoi(students[count].id_str);
        count++;
    }
    fclose(fp);
}

3. 結構體陣列排序 (qsort)

int compare_by_id(const void *a, const void *b) {
    const Student *sa = (const Student *)a;
    const Student *sb = (const Student *)b;
    return sa->id_num - sb->id_num;  // 升序
}

// 使用
qsort(students, count, sizeof(Student), compare_by_id);

4. 二分查找 (排序後)

Student *find_by_id(int target_id) {
    int left = 0, right = count - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (students[mid].id_num == target_id) return &students[mid];
        if (students[mid].id_num < target_id) left = mid + 1;
        else right = mid - 1;
    }
    return NULL;
}

5. 選單驅動主程式

void menu() {
    printf("\n1. 輸入資料\n2. 瀏覽全部\n3. 排序\n4. 查詢\n5. 存檔\n0. 離開\n選擇: ");
}

int main() {
    int choice;
    load_data("students.txt");
    
    while (1) {
        menu();
        scanf("%d", &choice);
        switch (choice) {
            case 1: input_student(); break;
            case 2: print_all(); break;
            case 3: qsort(students, count, sizeof(Student), compare_by_id); break;
            case 4: query_student(); break;
            case 5: save_data("students.txt"); break;
            case 0: return 0;
        }
    }
}

關鍵技術點總結

  • atoi 簡單但無錯誤回報,strtol 更健壯
  • qsort 需正確撰寫比較函數,轉型指標運算
  • 結構體陣列排序時整個結構體移動,大結構體可改排指標陣列
  • 檔案 I/O 需檢查返回值,防止格式錯誤導致無限迴圈
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved