我正在尝试通过搜索用户名来创建更改密码功能,如果找到确认传递,如果为真,则用newPass替换密码。
文件的写法如下:USERNAME; PASSWORD
我正在使用它来替换字符串,但不确定它的语法是否正确(im new)
tempPass.replace(0, tempPass.length(), newPass);
这是我目前的代码:
void AccountManager::changePassword(AccountManager & account) {
string username, password, newPass, passwordConf, tempUser, tempPass;
fstream openFile("UserPass.txt", ios_base::out | ios_base::in | ios_base::app);
// / Check if username exsists.
do {
cout << "Enter your username: " << endl;
getline(cin, username);
cout << "Enter you current password: " << endl;
getline(cin, password);
if (account.UserPass[username] != password) {
cout << "Username and password do not match. " << endl;
}
} while (account.UserPass[username] != password);
do {
cout << "Enter new password: " << endl;
getline(cin, newPass);
cout << "Retype password: " << endl;
getline(cin, passwordConf);
if (newPass != passwordConf) {
cout << "Password does not match confirmation. " << endl;
}
} while (newPass != passwordConf);
// /find / replace password with newPass in file
while (!openFile.eof()) {
getline(openFile, tempUser, ';');
getline(openFile, tempPass);
if ((tempUser == username) && (tempPass == password)) {
ofstream openFile("UserPass.txt", ios_base::app);
tempPass.replace(0, tempPass.length(), newPass); // changes pass in file at index ;+1
cout << "Password has been changed. " << endl;
switchLog(account); // Login on successful password change.
break;
}
}
account.UserPass[username] = newPass;
}
谢谢,
答案 0 :(得分:0)
您可以通过寻找文件的位置然后用完全替换相同数量的字节来替换数据,但是除非文件非常大并且替换发生,否则不鼓励这样做对于非常少量的数据。
编辑文件内容的正确方法是:
阅读Why is it not possible to erase contents from a file in C++?了解详情。