C++基于文件读写实现注册登录功能的登录模块开发疑问
C++ 注册登录功能登录模块实现方案
前置优化说明
- 原有注册逻辑默认覆盖文件内容,仅能存储1个用户,需改为追加模式才能存储多用户信息
- 读取文件前需要先清理
cin >> option留在输入缓冲区的换行符,避免getline首次读取到空内容
完整可运行代码
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { int option; int age, height; string name; string temp_str; ofstream file_out; ifstream file_in; cout << " For sign up type 1" <<endl; cout << " For log in type 2" <<endl; cin >> option; if ( option == 1 ) { // 新增ios::app参数,追加写入不覆盖原有内容 file_out.open("database.txt", ios::app); cout << "Input name: \n"; cin >> name; cout << "Input age: \n"; cin >> age; cout << " Input height: \n"; cin >> height; // 写入文件,每个用户固定占3行:姓名、年龄、身高 file_out << name << endl; file_out << age << endl; file_out << height << endl; file_out.close(); } else if (option == 2) { file_in.open("database.txt"); // 先判断文件是否打开成功 if (!file_in.is_open()) { cout << "未找到注册用户信息,请先注册!" << endl; return 0; } cout << "choose your username: " << endl; // 忽略cin残留的换行符 cin.ignore(); int index = 0; string uname; // 遍历所有用户,输出序号+用户名列表 while (getline(file_in, uname)) { cout << index << ":" << uname << endl; // 跳过当前用户的年龄、身高两行数据 getline(file_in, temp_str); getline(file_in, temp_str); index++; } // 提示用户输入选择的序号 int select; cout << "请输入你选择的用户序号:"; cin >> select; // 校验序号合法性 if (select < 0 || select >= index) { cout << "输入序号不合法!" << endl; file_in.close(); return 0; } // 重新打开文件定位到对应序号的用户信息 file_in.close(); file_in.open("database.txt"); string user_age, user_height; for (int i = 0; i <= select; i++) { getline(file_in, uname); getline(file_in, user_age); getline(file_in, user_height); } // 输出选中用户的完整信息 cout << "你选择的用户信息如下:" << endl; cout << "用户名:" << uname << endl; cout << "年龄:" << user_age << endl; cout << "身高:" << user_height << endl; file_in.close(); } return 0; }
核心逻辑说明
- 多用户存储实现:注册时给
open方法加ios::app参数,写入内容会追加到文件末尾,不会覆盖之前的用户数据 - 用户名列表展示:按行读取文件,每3行对应1个用户,第一行是用户名,直接按
序号:用户名格式输出,跳过后面两行的年龄、身高数据即可 - 用户信息读取:用户输入序号后,重新遍历文件到对应序号的位置,读取3行数据即可拿到对应用户的完整信息
内容的提问来源于stack exchange,提问作者T321
相关产品推荐
相关产品推荐

