How to remove data from the file i made?

I need to remove specific data from the file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <fstream>
#include <string>

using namespace std;
struct Teacher
{
    string name;
    string date;
};
int main()
{
    Teacher myTeacher;
    fstream myFile;
    myFile.open  ("sampleFile.txt",ios::in|ios::out|ios::app);

    for(int i=0;i<2;i++)
    {
        getline (cin,myTeacher.name);
        getline (cin,myTeacher.date);

        myFile<<myTeacher.name<<"\n"<<myTeacher.date<<"\n";

        }
string strOutput ;
myFile.seekg (0,ios::beg);

int lineCounter =1;
int numOflines= 2;

cout<<"NAME: \t\tSUBJECT:\n";

while(getline(myFile,strOutput))
{
    if (lineCounter==1)
        {
            myTeacher.name= strOutput;
            cout<<"\n"<<myTeacher.name;

        }
        else if(lineCounter==2)

        {
            myTeacher.date=strOutput;
            cout<<"\t\t"<<myTeacher.date;

        }
        if(lineCounter==numOflines)
        {
            lineCounter=0;
        }
        lineCounter++;
}
myFile.close();
cout<<endl;
return 0;

}
1) Read the file into memory (such as an array or vector)
2) Modify the memory to delete the unwanted information
3) Write the memory back to file

Hope this helps.
Noted

can you help me to understand more about the tip number 1?
Sure.

Presumably you have a file of Teachers ("teachers.txt" or something).

Allen Birch
0000/00/00
Jim Brown
0000/00/00
Jennifer Black
0000/00/00


You will need something to keep track of all those teachers, like a vector (preferred) or an array.

1
2
3
std::vector<Teacher> teachers;
constexpr int MAX_NUM_TEACHERS 50;
Teacher teachers[MAX_NUM_TEACHERS];
int num_teachers = 0;

Create yourself a function to read the teachers into memory:

1
2
3
4
5
6
7
8
9
10
11
12
13
void load_teachers( 
  const std::string& filename,
  std::vector <Teachers> & teachers )
{
  std::ifstream f( filename );
  Teacher teacher;
  while (
         getline( f, teacher.name )
    and  getline( f, teacher.date ))
  {
    teachers.push_back( teacher );
  }
}
void load_teachers( 
  const std:string& filename, 
  Teacher* teachers, int* num_teachers )
{
  std::ifstream f( filename );
  Teacher teacher;
  while ((*num_teachers < MAX_NUM_TEACHERS)
    and  getline( f, teacher.name )
    and  getline( f, teacher.date ))
  {
    teachers[(*num_teachers)++] = teacher;
  }
}

You can the load your teachers from file:

 
load_teachers( "teachers.txt", teachers );
load_teachers( "teachers.txt", teachers, &num_teachers );

Good luck!
Last edited on
owkkk i m going to study taht
excuse me i plan to use array as to keep track of all those teachers


can you show me how to start?
Topic archived. No new replies allowed.