c++实现注册和登录
时间: 2023-07-25 17:15:26 浏览: 59
以下是一个简单的 C++ 程序实现注册和登录功能,使用文件来保存用户信息。为了简化程序,这里没有实现密码加密等安全性相关的功能,仅供参考:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct User {
string username;
string password;
};
vector<User> users;
// 读取用户信息
void read_users() {
ifstream fin("users.txt");
string username, password;
while (fin >> username >> password) {
users.push_back({username, password});
}
fin.close();
}
// 写入用户信息
void write_users() {
ofstream fout("users.txt");
for (auto user : users) {
fout << user.username << " " << user.password << endl;
}
fout.close();
}
// 注册
void register_user() {
User user;
cout << "请输入用户名: ";
cin >> user.username;
cout << "请输入密码: ";
cin >> user.password;
users.push_back(user);
write_users();
cout << "注册成功!" << endl;
}
// 登录
void login() {
string username, password;
cout << "请输入用户名: ";
cin >> username;
cout << "请输入密码: ";
cin >> password;
for (auto user : users) {
if (user.username == username && user.password == password) {
cout << "登录成功!" << endl;
return;
}
}
cout << "用户名或密码错误!" << endl;
}
int main() {
read_users();
int choice;
while (true) {
cout << "请选择操作:" << endl;
cout << "1. 注册" << endl;
cout << "2. 登录" << endl;
cout << "3. 退出" << endl;
cin >> choice;
switch (choice) {
case 1:
register_user();
break;
case 2:
login();
break;
case 3:
return 0;
default:
cout << "无效的选项!" << endl;
}
}
return 0;
}
```
在上述程序中,用户信息保存在一个 users 的 vector 中,通过文件读写来实现注册和登录功能。注册时,程序会提示用户输入用户名和密码,然后将信息保存到 users 中,并写入到文件中。登录时,程序会提示用户输入用户名和密码,然后在 users 中查找是否存在匹配的用户,如果存在,则登录成功;否则,提示用户名或密码错误。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)