以下是我遇到的代碼,我有一個.txt文件,其中包含使用此格式的用戶及其密碼列表:user;password
。 我需要在文件中搜索用戶,然後刪除包含此用戶的行。在C++中使用istream/ofstream刪除txt文件中的特定行
void deleteauser()
{
string user;
cout<<"Which user do you wish to delete?";
cin>>user;
string line;
string delimiter=";";
string token,token1;
ifstream infile;
infile.open("users.txt",ios::in);
while (getline(infile,line,'\n'))
{
token = line.substr(0, line.find(delimiter));
token1=line.substr(token.length(), line.find('\n'));
if(token==user)
{
//here i need to delete the line of the user that has been found
}
}
infile.close();
}
這聽起來不夠低效嗎? – srph
@srph這只是處理這種事情的最常見方法。另一種方法是將所有文件讀入內存,並寫出所需的數據,但如果文件很大或者您不知道它的大小,則需要更多的工作。 –