提问人:EdwardTheTrain 提问时间:10/8/2023 更新时间:10/8/2023 访问量:85
消失的内容 c++ 写入文件
Disappearing content c++ writing to file
问:
每当我在重新运行代码后将数据写入文件时,文件的内容都会消失
#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();
}
我正在检查该文件以将用户名写入单独的代码行。
答:
4赞
Ahmed AEK
10/8/2023
#1
默认的打开模式会删除文件内容,如果希望文件保留其以前的内容,请在模式下打开文件。append
ofstream file(path, std::ios::app);
评论