【发布时间】:2021-07-20 08:52:53
【问题描述】:
当我编辑该值时,它不会替换记事本中的原始值。如何在 C++ 中更新文件中的数据而不显示旧数据?我想删除特定数据并更新。
str_ID = to_string(ID);
cout<<"\tEnter ID to edit: ";
cin>>value;
if(value == str_ID){
cout<<"\tThe Member is available"<<endl;
ifstream myfile2;//File to read from
myfile2.open("editfile.txt");
ofstream temp; //Temporary file
temp.open("temp.txt");
while (getline(myfile2, line))
{
if (line != str_ID)
temp << line << endl;
}
while (getline(myfile2,line)){
line.replace(line.find(str_ID),str_ID.length(),"");
temp<<line<<endl;
}
myfile2.close();
temp.close();
remove("editfile.txt");
rename("temp.txt", "editfile.txt");
cout<<"\tEnter name :";
cin>>name;
cout << "\tENTER IC : ";
cin>> IC;
cout << "\tENTER AGE : ";
cin>> age;
cout << "\tENTER GENDER (F / M): ";
cin>> gender;
ofstream myfile;
myfile.open("editfile.txt", ios::app | ios::out);
myfile<<ID;
myfile<<"\t"<<name;
myfile<<"\t"<<IC;
myfile<<"\t"<<gender<<endl;
}
【问题讨论】:
-
您的第二个循环将不起作用,因为文件指针将放在文件末尾。您只想用新的 str_ID 替换旧的 str_ID 吗?请更准确地解释您想要做什么。
-
我正在创建一个管理程序。我想在其中添加、编辑、删除和查看功能。我在编辑部分苦苦挣扎。在记事本中添加并保存数据后,我想对其进行编辑。我希望它替换那个特定的数据。
标签: c++ windows coding-style edit notepad