首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 學生信息管理系統:從輸入到查詢的完整實現

     編輯:程式設計綜合問答

需求分析

錄入 N 名學生的 學號、姓名、性別,支持按任意字段(如姓名)查詢並顯示完整信息。

數據結構設計

struct Student {
    int    id;        // 學號
    string name;      // 姓名
    int    gender;    // 0=女 1=男
};

使用 vector 動態存儲,避免手動 new/delete。

核心代碼

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct Student { int id; string name; int gender; };

void printStudent(const Student& s) {
    cout << "學號:" << s.id << " 姓名:" << s.name << " 性別:" << (s.gender?"男":"女") << '\n';
}

int main() {
    int n;
    cout << "請輸入學生人數: ";
    if(!(cin >> n) || n <= 0) return 0;

    vector stu(n);
    for(int i=0; i> stu[i].id >> stu[i].name >> stu[i].gender;
    }

    // 查詢演示:按姓名查找
    string queryName;
    cout << "\n請輸入要查詢的姓名: ";
    cin >> queryName;

    auto it = find_if(stu.begin(), stu.end(),
        [&](const Student& s){ return s.name == queryName; });

    if(it != stu.end()) {
        cout << "查詢結果:\n";
        printStudent(*it);
    } else {
        cout << "未找到該學生。\n";
    }
    return 0;
}

進階擴展建議

  • 多字段查詢:封裝 query(vector&, function) 通用查詢函數。
  • 持久化:用 fstream 讀寫 CSV/二進制文件,或嵌入 SQLite。
  • 菜單交互:while(true){ showMenu(); switch(cmd){...} } 實現增刪改查循環。

避坑提醒

  1. cin >> name 遇空格截斷,含空格姓名請用 getline(cin, name)(注意前置換行符處理)。
  2. 性別輸入建議做合法性檢查 while(gender!=0 && gender!=1) re-input。
  3. 動態數組首選 vector,若必須用指針請配對 delete[]。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved