Untitled

 avatar
unknown
plain_text
2 years ago
2.5 kB
4
Indexable
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio> // Include the <cstdio> header for removing the file

using namespace std;

struct Student {
    int id;
    string name;
};

void writeStudentData(const string& filename, const Student& student) {
    ofstream outFile(filename, ios::app);
    if (outFile.is_open()) {
        outFile << student.id << " " << student.name << "\n";
        outFile.close();
        cout << "Student information has been written to the file." << endl;
    } else {
        cerr << "Error: Unable to open the file for writing." << endl;
    }
}

void readStudentData(const string& filename) {
    ifstream inFile(filename);
    if (inFile.is_open()) {
        Student student;
        while (inFile >> student.id) {
            inFile.get();
            getline(inFile, student.name);
            cout << "Student ID: " << student.id << ", Student Name: " << student.name << endl;
        }
        inFile.close();
    } else {
        cerr << "Error: Unable to open the file for reading." << endl;
    }
}

void deleteFileContents(const string& filename) {
    ofstream outFile(filename, ios::trunc); // Open the file in truncation mode
    if (outFile.is_open()) {
        outFile.close();
        cout << "File contents have been deleted." << endl;
    } else {
        cerr << "Error: Unable to open the file for deletion." << endl;
    }
}

int main() {
    const string filename = "student_data.txt";

    while (true) {
        cout << "Choose an option:\n";
        cout << "1. Add a student\n";
        cout << "2. Display all students\n";
        cout << "3. Delete file contents\n"; // Add a fourth option
        cout << "4. Quit\n"; // Update the Quit option
        int choice;
        cin >> choice;

        if (choice == 1) {
            Student student;
            cout << "Enter student ID: ";
            cin >> student.id;
            cin.ignore();
            cout << "Enter student name: ";
            cin.ignore();
            getline(cin, student.name);

            writeStudentData(filename, student);
        } else if (choice == 2) {
            readStudentData(filename);
        } else if (choice == 3) {
            deleteFileContents(filename); // Call the new function
        } else if (choice == 4) {
            break;
        } else {
            cout << "Invalid choice. Please choose a valid option." << endl;
        }
    }

    return 0;
}
Editor is loading...