需求:現有學生資料文字檔,支援「尾端新增一行」、「依學號刪除指定行」。
struct Student {
long long Sno; string Sname, Ssex; int Sage; string Sdept;
// CSV 序列化
string toCsv() const { return to_string(Sno) + ',' + Sname + ',' + Ssex + ',' + to_string(Sage) + ',' + Sdept; }
static Student fromCsv(const string& line) {
Student s; size_t p=0, q;
for (int i=0; i<5; ++i) {
q = line.find(',', p);
string tok = line.substr(p, q-p);
if (i==0) s.Sno = stoll(tok);
else if (i==1) s.Sname = tok;
else if (i==2) s.Ssex = tok;
else if (i==3) s.Sage = stoi(tok);
else s.Sdept = tok;
p = (q==string::npos) ? line.size() : q+1;
}
return s;
}
};
vector load(const string& fn) {
vector v; ifstream in(fn); string line;
while (getline(in, line)) if (!line.empty()) v.push_back(Student::fromCsv(line));
return v;
}
void save(const string& fn, const vector& v) {
ofstream out(fn); for (auto& s : v) out << s.toCsv() << '\n';
}
// 尾端新增
void append(const string& fn, const Student& s) {
auto v = load(fn); v.push_back(s); save(fn, v);
}
// 依學號刪除
bool removeBySno(const string& fn, long long sno) {
auto v = load(fn);
auto it = remove_if(v.begin(), v.end(), [sno](const Student& s){ return s.Sno == sno; });
if (it == v.end()) return false;
v.erase(it, v.end());
save(fn, v);
return true;
}
int main() {
const string FILE = "students.csv";
while (true) {
cout << "1.新增 2.刪除 3.列表 0.退出\n選項: ";
int opt; if(!(cin>>opt)) break;
if (opt==0) break;
if (opt==1) {
Student s; cout << "學號 姓名 性別 年齡 系所: ";
cin >> s.Sno >> s.Sname >> s.Ssex >> s.Sage >> s.Sdept;
append(FILE, s); cout << "新增完成\n";
} else if (opt==2) {
long long sno; cout << "刪除學號: "; cin >> sno;
cout << (removeBySno(FILE, sno) ? "刪除成功" : "查無此學號") << '\n';
} else if (opt==3) {
for (auto& s : load(FILE)) cout << s.toCsv() << '\n';
}
}
}
用 `struct` + `vector` + `CSV` 即可輕鬆實現「尾端新增、依鍵刪除、全檔列表」,代碼清晰、易維護、Excel 互通。