我有一个包含用户名和密码的向量。我正在尝试执行“重置新密码”功能,我首先在向量中搜索用户名是否存在, 接下来,用户将提示输入新密码,旧密码将替换为新密码。
但我遇到了这个错误
Invalid operands to binary expression ('User' and 'const std::__1::basic_string<char>')
因为这条线。
replace(userDetails.begin(), userDetails.end(), oldPassword, newPassword);
我的部分代码与问题相关
string name;
cout << "Please enter a user name that the password will be reset \n";
cin >> name;
for (int i =0; i<userDetails.size(); i++) {
if (userDetails[i].getUserName() == name) {
string newPassword;
string oldPassword;
oldPassword = userDetails[i].getPassword();
cout << "Please enter a new password" << endl;
cin >> newPassword;
replace(userDetails.begin(), userDetails.end(), oldPassword, newPassword);
cout << userDetails[i].getPassword();
}
}
我不确定应该怎么做以达到我想要的效果。请帮忙。感谢
答案 0 :(得分:2)
第一个问题在第
行replace(userDetails.begin(), userDetails.end(), oldPassword, newPassword);
您正尝试将User
对象替换为std::string
对象。
第二个问题(如 nm 所述) - 您不需要在循环内使用基于范围的函数(replace()
或其他)当你已经掌握正确的User
对象时。
您可以使用std::find_if()
函数查找具有正确名称的User
对象,而不是编写循环。在C ++ 11中,它可能是这样的:
auto user = find_if(userDetails.begin(), userDetails.end(),
[&name](const User& u){return u.getUserName()==name;});
在预C ++ 11代码中,你需要一个单独的谓词函数而不是lambda /你自己的搜索循环(当找到用户时只需break;
)。
如果找到用户,您可以设置密码:
if(user != userDetails.end()){
// (ask for the new password here)
user->setPassword(newPassword); // assuming you have a setter for password field
}
答案 1 :(得分:1)
您的userDetails
容器似乎包含User
个对象,但您将其视为包含std::string
s。您应该替换userDetails[i]
的密码。如何做到这一点取决于User
类的详细信息。
你可能想要这样的东西,使用std::find_if
和合适的谓词来查找用户名等于name
的第一个用户:
// find the right User
auto it = std::find_if(userDetails.begin(),
userDetails.end(),
[&name](const User& user)
{ return user.getUserName() == name;})
然后替换该用户的密码:
if (it != userDetails.end()) {
// we found a user with username == name
it->setPasswd(newPasswd);
} else
// no user found with that username
std::cout << "User " << name << " not found" << std::endl;
}