网站编程需要什么语言2345导网址导航下载
使用vector实现一个简单的本地注册登录系统
注册:将账号密码存入vector里面,注意防重复判断
登录:判断登录的账号密码是否正确
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>using namespace std;// 用户账户结构体
struct UserAccount {string username;string password;UserAccount(const string& uname, const string& pwd) : username(uname), password(pwd) {}
};// 账户管理系统类
class AccountSystem {
private:vector<UserAccount> accounts; // 存储所有账户// 检查用户名是否已存在bool isUsernameExist(const string& username) const {return any_of(accounts.begin(), accounts.end(), [&username](const UserAccount& acc) {return acc.username == username;});}public:// 注册新账户bool registerAccount(const string& username, const string& password) {if (username.empty() || password.empty()) {cout << "用户名和密码不能为空!" << endl;return false;}if (isUsernameExist(username)) {cout << "用户名已存在,请选择其他用户名!" << endl;return false;}accounts.emplace_back(username, password);cout << "注册成功!" << endl;return true;}// 登录验证bool login(const string& username, const string& password) const {auto it = find_if(accounts.begin(), accounts.end(), [&username](const UserAccount& acc) {return acc.username == username;});if (it == accounts.end()) {cout << "用户名不存在!" << endl;return false;}if (it->password != password) {cout << "密码错误!" << endl;return false;}cout << "登录成功!欢迎," << username << "!" << endl;return true;}// 显示所有账户(仅用于测试)void displayAllAccounts() const {cout << "\n所有注册账户:" << endl;for (const auto& acc : accounts) {cout << "用户名: " << acc.username << ", 密码: " << acc.password << endl;}}
};// 主菜单
void displayMenu() {cout << "\n===== 账户系统 =====" << endl;cout << "1. 注册" << endl;cout << "2. 登录" << endl;cout << "3. 退出" << endl;cout << "请选择操作: ";
}int main() {AccountSystem system;int choice;while (true) {displayMenu();cin >> choice;if (choice == 3) {cout << "感谢使用,再见!" << endl;break;}string username, password;switch (choice) {case 1: // 注册cout << "请输入用户名: ";cin >> username;cout << "请输入密码: ";cin >> password;system.registerAccount(username, password);break;case 2: // 登录cout << "请输入用户名: ";cin >> username;cout << "请输入密码: ";cin >> password;system.login(username, password);break;default:cout << "无效选择,请重新输入!" << endl;break;}// 测试用:显示所有账户// system.displayAllAccounts();}return 0;
}
牛客网练习: