An example of reading from the file into a vector, and deleting from the vector. This program doesn't modify the file. To do that, write out the contents of the vector to the file after making changes.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
usingnamespace std;
struct Student {
int id;
string name;
string program;
};
// Function to read a Student from a file
bool readStudent(std::istream & is, Student & st)
{
is >> st.id; is.ignore(100, '\n');
getline(is, st.name);
getline(is, st.program);
return is;
}
// Function to display a Student
void showStudent(std::ostream & os, const Student & stud)
{
os << "\nStudent ID : " << stud.id;
os << "\nStudent Name : " << stud.name;
os << "\nStudent Program : " << stud.program;
os << '\n';
}
int main()
{
ifstream data("data.txt");
if (!data)
{
cout << "\nError Opening The File\n";
cin.get();
return 1;
}
// Define a vector to store the entire file contents
std::vector<Student> students;
// Read all Students from file into vector
Student stud;
while (readStudent(data, stud))
{
students.push_back(stud);
}
char choise = '1';
while (choise == '1')
{
// Display all the contents of the vector
for (size_t i=0; i<students.size(); ++i)
showStudent(cout, students[i]);
cout << "\nEnter The Student ID to be deleted : ";
int id;
cin >> id;
// find and delete Student from vector
for (auto it = students.begin(); it!=students.end(); ++it)
{
if (id == it->id)
{
students.erase(it);
break;
}
}
cout << "\n1 to try again : ";
cin >> choise;
}
}
Student ID : 12345
Student Name : Muhammad Salman Zafar
Student Program : BS(CS)
Student ID : 12346
Student Name : Muhammad Waleed Karam
Student Program : BS(SE)
Enter The Student ID to be deleted : 12346
1 to try again : 1
Student ID : 12345
Student Name : Muhammad Salman Zafar
Student Program : BS(CS)
Enter The Student ID to be deleted : 0
1 to try again : 0