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

C++ TXT 檔案插入/刪除行:以學號為鍵值的 Vector+CSV 模式

     編輯:程式設計疑難解答

需求:現有學生資料文字檔,支援「尾端新增一行」、「依學號刪除指定行」。

資料結構:`struct Student` + `vector` 記憶體模型


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';
        }
    }
}

關鍵優勢

  • **CSV 格式**:欄位含空格/中文不易解析錯位,Excel 直開即用。
  • **Vector + 算法**:`remove_if` + `erase` 刪除簡潔,`push_back` 新增 O(1)。
  • **原子存檔**:`save` 先寫 `.tmp` 再 `rename`,避免斷電損檔。
  • **擴充性**:需查詢/修改/排序只需在 Vector 上操作,再 `save` 即可。

大檔案 (>100MB) 建議

  • 改用 **SQLite** (`DELETE FROM student WHERE Sno=?`),獲得索引、事務、並發。
  • 或維護 **B+ 樹索引檔** (學號 → 檔案位移),實現 O(log n) 定位修改。

用 `struct` + `vector` + `CSV` 即可輕鬆實現「尾端新增、依鍵刪除、全檔列表」,代碼清晰、易維護、Excel 互通。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved