I have a list of names and I want to write them to file called (newfile) and then push them in vector and then i want to add a name to a list so i will push it in the same vector and then iam trying to write again the update list in the same file. how can i delete the previous lines in the file and write a new lines.the other thing when i want to compare new name if its exists in the list and when i check with the vector it always check with the original list. Here is my codes for both functions.Please can any one help.Thanks

void loadfile(){
ifstream myfile;
string line;
int a=0;
myfile.open("newfile.txt");
  if (myfile.is_open())
    {
    // Read the file until it's finished, displaying lines as we go.
    
    while (!myfile.eof())
      {
     
      getline(myfile, line, '\n'); // getline reads a line at a time
      residents.push_back(line);
      a++;
      }

    myfile.close();
    }
  else   // Some kind of error opening the file
    {
    cout << "ERROR: Could not open the newfile: " <<myfile << endl;
    exit(1);
    }
}



void UpdateFile(){
					
	ofstream myfile;
	myfile.open("newfile.txt");
	if (myfile.is_open())
	{
          for (int a=0; a<(residents.size()); a++)           
	myfile << residents[a] << endl;
	myfile.close();
	}
	else
	{
	cout << "ERROR: could not open file: " << "newfile.txt" << endl;cout  "If      absent, please create an EMPTY dat file named " << "newfile.txt"  << " in directory." << endl;
	}
	}

>> how can i delete the previous lines in the file and write a new lines

You will have to rewrite the entire file. It's not possible to insert new lines somewhere in the middle of a text file without rewriting it. You already have the vector, so just interate through it and write the strings to the file.

As for your other question -- can't say what's wrong from the code snippet you posted. Will need to see the entire program.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.