Vectors and files, Problem with erasing elements

I have a problem with a part of a program I've been working with.
The menu allows the user to 1.Show the names that are written in a txt, 2. Remove a name, and 3. Add a name. To do that it uses three functions. The problem lies with the Remove name function. The function reads the names and places them in a
vector named list. After that, the names are presented to the user and he types the one he wants deleted (stored in string choice).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
for(int i = 0; i < list.size(); ++i)
      {
	  if(list[i] == choice)
	  {
              list.erase(list.begin() + i);
               
              ofstream outfile;
              outfile.open (filename.c_str());
              if (outfile.is_open())      
               {
                  for (i = 0; i < list.size(); i++)
                  {
                     outfile << list[i] << endl;
                  }
                  outfile.close();
               }
          }
     }

The problem is that when the function saves the names, after it removed the chosen name, it adds a blank row at the end of the file, and when I try to add a name with the other function that blank row is annoying. If I attempt to remove more names, then the blank rows increase as well. And the names I add, are added after all the blank rows

I tried opening the file to save the names after the deletion, using
outfile.open (filename.c_str(), ios::out | ios::trunc);
but it didn't solve the problem.

Then I decided to check the list.size() right before and after the: list.erase(list.begin() + i);. It shows that the size is indeed reduced(from 11 to 10). After that, the list is saved in the NameList.txt with the extra blank row.

Right now the function saves to the txt after each change to the list of names. I don't like that now and I believe it would be better if it saved only once - when control returns to main(). I think I'll write the function from scratch, but it would be good for me to know what is wrong with this one.

I know I didn't post the whole program, but it is quite long. Hopefully it is something stupid I've missed, and you'll be able to help me. It's frustrating. After two months of absence due to an accident, it feels I start from scratch again.
Last edited on
Topic archived. No new replies allowed.