I am creating a program which allows a user to enter and store various data about a pet. Case 3 should allow the user to delete a pet from the file, however the code I have compiles but does not delete any data from my "pet.txt file. Attached is the full code but case 3 is where my issues are. How do I properly remove and rename this file with my program?
the modern c++ way is https://en.cppreference.com/w/cpp/filesystem
the "I can't use that" simple way is operating system commands.
system("del filename"); //filename is the text, not a variable here...
system("ren name name2");
and similar unix commands (rm and probably cp or move? you can look it up)
you can also do c++ to make a new file and open the old one, copy the contents, and then clear the old file but actually removing the now empty file from the OS I do not know.
As jonnin pointed out, the proper way is to use <filesystem> (requires C++17).
If that's not an option for you, here the routines I used before I went to C++17.
You are only allowing data for 1 pet to be stored. Every time you use option 1 you erase the previous data before saving the new data. Hence option 2) doesn't need to ask for the pet name (which isn't used). Likewise for option 3). You don't ask for the pet name as there's data for only 1 per stored.
option 2) should also check that the file has been opened ok.
So for option 3), all that's needed is to remove all the data from the file. An easy way to do this is simply:
1 2 3 4 5
case 3:
{
ofstream fw("pet.txt");
}
break;
This will open/create the file, erase any existing contents and then close the file.