I'm creating a program that will create a "company" profile (not actually used by companies), and the profiles will save to a .txt file, which works fine but When you run the program again, any profiles from previous sessions that existed will be overwritten by new profiles
(e.g: 2 profiles from an older session, one new profile is created and that profile overwrites the 1st profile)
Is it possible to have it so no profile is overwritten? I cant post my source code because it's very long, but you should be able to view the entire code and the .txt file on replit where I've posted it
#include <fstream>
#include <iomanip>
#include <iostream>
usingnamespace std;
// Profile Creation
int main(int argc, constchar *argv[]) {
double height[100] =
{}; // Arrays for the Heights that will be recorded into the program
int age[100] =
{}; // Arrays for the Ages that will be recorded into the program
string name[100] =
{}; // Arrays for the names that will be recorded into the program
string name2[100] = {};
string name3[100] = {};
int count;
int count2;
fstream data;
data.open("profiles.txt");
for (int d = 0; d < count; d++) {
data << "\n"<< name2[d] << ", " << name[d] << " " << name3[d] << " " << age[d] << " Years old, " << height[d] << " Centimeters tall\n";
}
data.close();
}
Bits of the code that is most relevant, if it looks weird it's because its spliced together but it should still work fine
Files will be wiped when opened for writing unless you specify that you are appending.
Also, it's generally cleaner to either use ofstream (output) or ifstream (input), as it makes it immediately obvious what the file stream is being used for.
constexprint MAX_NUM_PROFILES = 100;
Profile profiles[MAX_NUM_PROFILES];
int num_profiles = 0;
3.
Read all the profiles from “profiles.txt” into the array/vector/whatever when your program starts. Remember to keep track of how many you have read. Make yourself a function to do it.
ifstream f("profiles.txt");
while (read_profile( f, profiles[num_profiles] ))
{
num_profiles += 1;
if (num_profiles > MAX_NUM_PROFILES) break;
}
4.
Modify the array/vector/whatever.
5.
Write all the profiles back to “profiles.txt”.
You can structure your “profiles.txt” file any way you wish, but it is really not useful to put unnecessary information in it. My example version just uses a line for each piece of information.
1 2 3 4 5 6 7 8 9 10
Tomas
Stanley
Holland
172
25
Zendaya
Maree Stoermer
Coleman
178
25
Only when your program presents this information to the user does it need to say things like Robert Downey Jr. is 173 centimeters tall.