I wanted to delete data from my original text file "PHONE.txt" while my temp text file is "newPHONE.txt"..but after i do deletion the text only remove at temp file but not in original file..any kind soul can help me? Thanks!

else if(userInput == "Delete"||userInput == "delete")
    {
        string line;
			ifstream in("PHONE.txt"); // open input file
			if( !in.is_open())
			{
				cout << "Input file failed to open\n";
				return 1;
			}


			// loop to read/write the file. Note that you need to add code here to check
                                         // if you want to write the line
			ofstream out("newPHONE.txt");// now open temp output file
			string DeleteData,Name,Phone;
			cout<<"Enter your data to delete : ";
			cin>>Name;
			DeleteData = Name;

			cout<<"\n\nData to delete is : "<<DeleteData;
			cout<<endl;

			int a = 0;
			bool del=false;;

			while( getline(in,line) )
			{
				if (a==0)
				{
					if(line != DeleteData)
					{
						out << line;
						del = false;
					}
					else
					{
						del = true;
					}
				}
				else
				{
					if(del==true && ((a-1)==0) )
					{
						if(line != DeleteData)
							out << line;
					}
					else
					{
						if(line != DeleteData)
						{
							out << "\n" << line;
						}
					}
				}

				a++;
			}

			in.close();
			out.close();

			remove("PHONE.txt");// delete the original file
			rename("newPHONE.txt","phone.txt");// rename old to new

    }

The data to delete should be determined before the actual delete action is taking place.

1) Read the original file
2) Ask for stuff to be deleted (pass that list to the function to delete)
3) Write temp file omitting the deleted names
4) Delete original file, rename temp file to original file.

Edited 4 Years Ago by thines01: clarity

This article has been dead for over six months. Start a new discussion instead.