2014-01-05 70 views
0

我有一個包含用戶名和密碼的向量。我試圖做一個「重置新密碼」功能,我首先在向量中查找用戶名是否存在用戶名, 然後接下來用戶會提示輸入新密碼,舊密碼將被替換爲新的那一個。使用std :: replace時,無效的操作數爲二進制表達式C++

但我遇到這個錯誤

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

嘗試你的'* Password'變量重命名爲'foo'和'bar'。違規線路是否仍然像以前一樣替換相同的東西?看看'std :: replace'的實際文檔也可以提供幫助。 –

回答

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; 
} 
+0

所以你的意思是我不應該使用持有對象的矢量,而只是一個保存字符串的普通矢量呢? – user2947249

+0

@ user2947249不,只需替換相關對象中的密碼即可。 – juanchopanza

+0

你介意舉個例子嗎?對不起,我在C++中不太好。仍處於初級階段 – user2947249

2

第一個問題是在線

replace(userDetails.begin(), userDetails.end(), oldPassword, newPassword); 

您試圖用std::string對象替換User對象。

(由N.M.提到的)第二個問題 - 你不需要使用基於範圍的函數(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的代碼,你需要一個單獨的謂詞函數,而不是拉姆達/你自己的搜索循環(只是break;當發現用戶)。

如果發現用戶可以設置密碼:

if(user != userDetails.end()){ 
    // (ask for the new password here) 
    user->setPassword(newPassword); // assuming you have a setter for password field 
} 
+1

您想查找所有擁有相同密碼X的用戶,強制他們全部使用新密碼Y,對嗎?這是一種令人耳目一新的安全方法,但可能並非OP的想法。 –

+0

哦,謝謝!我對方法更感興趣,而不是細節。編輯:) –

+0

看看代碼,他已經有正確的用戶記錄在手... –

相關問題