ARTICLE AD BOX
Rather than a search followed by an insertion if the user name isn't present, you may prefer to do an insert, then check the result to see if that succeeded. If it failed, that (at least normally) means it was already present, so they need to try a different user name.
bool addUser(std::string const &user_name, std::string const &password) { auto ret = data.insert({user_name, {password, 0.0}}); return ret.second; }A lot depends on whether this is throwaway code (e.g., a classroom assignment) or something you intend to put to real use.
If you're using it in the real world, authenticating a user becomes quite a non-trivial task in itself.
You normally want to not store raw passwords. Instead, you usually want to store the hash of a passowrd. You usually want to use "salt" with the password. The salt is publicly available, but you want to generate a unique salt for each user's password, so an attacker can't easily do a dictionary attack on the passwords (i.e., hash a lot of common words and names and find users who've used something like their middle name, their SO's first name, etc.) In theory they can do that in spite of your using salt, but salt means they need to do the job separately for each user, making it much more expensive. If you're using it over a network, you don't want to send the password as clear text, so you either use an encrypted connection (e.g., TLS) or you use a challenge/response protocol. You usually want to include some recovery method, in case the user forgets their password (which happens constantly).495k83 gold badges657 silver badges1.2k bronze badges
std::map has a find() method to search for an existing key, eg:
auto iter = userdatabase.find(username); if (iter != userdatabase.end()) { // username found // use *iter if needed to access their Userlogin } else { // username not found }For example:
#include <iostream> #include <map> #include <string> struct Userlogin { std::string password; double balance; }; int main(){ std::string user_name, password, new_user; std::map<std::string, Userlogin> user_db; std::cout << "Welcome to the 777 machine\n"; std::cout << "Did you want to create a new account?: "; std::cin >> new_user; if (new_user = "Yes" || new_user = "y" || new_user = "Y") { do { std::cout << "Please enter your new username: "; std::cin >> user_name; if (user_db.find(user_name) == user_db.end()) break; } std::cout << "\nThat username is already taken.\n"; } while (true); std::cout << "\nPlease enter your new password: " std::cin >> password; Userlogin login; login.password = password; login.balance = 0.0; user_db[user_name] = login; } return 0; }610k36 gold badges517 silver badges875 bronze badges
Explore related questions
See similar questions with these tags.
