Untitled
unknown
plain_text
2 years ago
2.2 kB
3
Indexable
#include <iostream> #include <fstream> #include <string> struct Student { int id; std::string name; }; // Function to write student information to a file void writeStudentData(const std::string& filename, const Student& student) { std::ofstream outFile(filename, std::ios::app); // Open the file in append mode if (outFile.is_open()) { outFile << student.id << " " << student.name << "\n"; outFile.close(); std::cout << "Student information has been written to the file." << std::endl; } else { std::cerr << "Error: Unable to open the file for writing." << std::endl; } } // Function to read and display student information from a file void readStudentData(const std::string& filename) { std::ifstream inFile(filename); if (inFile.is_open()) { Student student; while (inFile >> student.id) { std::getline(inFile, student.name); std::cout << "Student ID: " << student.id << ", Student Name: " << student.name << std::endl; } inFile.close(); } else { std::cerr << "Error: Unable to open the file for reading." << std::endl; } } int main() { const std::string filename = "student_data.txt"; while (true) { std::cout << "Choose an option:\n"; std::cout << "1. Add a student\n"; std::cout << "2. Display all students\n"; std::cout << "3. Quit\n"; int choice; std::cin >> choice; if (choice == 1) { Student student; std::cout << "Enter student ID: "; std::cin >> student.id; std::cin.ignore(); // Consume the newline character std::cout << "Enter student name: "; std::cin.ignore(); std::getline(std::cin, student.name); writeStudentData(filename, student); } else if (choice == 2) { readStudentData(filename); } else if (choice == 3) { break; } else { std::cout << "Invalid choice. Please choose a valid option." << std::endl; } } return 0; }
Editor is loading...