錄入 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){...} } 實現增刪改查循環。cin >> name 遇空格截斷,含空格姓名請用 getline(cin, name)(注意前置換行符處理)。while(gender!=0 && gender!=1) re-input。vector,若必須用指針請配對 delete[]。