Reputation: 45
Whenever I write the data into the file after rerunning the code the contents of the file disappears
#include <iostream>
#include <fstream>
using namespace std;
int main(){
string username = "";
string path = "/Users/kishorejyothi/Desktop/C++/practice/list_usernames.txt";
ofstream file(path);
if(file.fail()){
cerr << "Failed process";
exit(1);
}
cout << "Enter a username: ";
cin >> username;
string full_username = username.append("@Abhinav.com");
if(username.empty()){
cout << "You didn't enter your username";
}
else{
cout << "Thanks for entering your preferred username." << endl;
cout << "Your username is now " << full_username;
}
file << username << endl;
file.close();
}
I was exxpecting the file to write the usernames on seperaate lines of code.
Upvotes: 3
Views: 174
Reputation: 18090
the default open mode deletes the file content, open the file in append
mode if you want it to keep its previous content.
ofstream file(path, std::ios::app);
Upvotes: 4