gpt4 book ai didi

c++ - 检查用户是否存在(所有用户帐户都存储在一个文件中)

转载 作者:行者123 更新时间:2023-11-28 07:30:51 25 4
gpt4 key购买 nike

我正在学习 C++ 中的文件处理。只是为了测试我写了这个小代码。基本上我想做的是使用文件处理制作一个用户帐户程序。所以我想在我的程序中使用 if elsewhile 来比较文件中的数据。

例如,如果用户输入他的用户名“john”,程序应该能够在文件中搜索名字 john,如果它存在,它应该允许用户登录并使用相同的密码。

我写的代码只是文件写入测试。请帮我解决实际代码。我是初学者,如果太傻了,我很抱歉。

谢谢!

#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<fstream>
#include<string.h>

using namespace std;
void main () {
ofstream file;
file.open("C:\tests1.txt", ios::trunc);

char name[50];
cout<<"\nEnter your name: ";
cin>>name;
file<<"Username: "<<name;
file.close();
cout<<"Thank you! Your name is now in the file";

ifstream file("tests1.txt");
if(file=="Username: Chinmay") {
cout<<"If else successfull\n";
} else {
cout<<"If else failed\n";
}
_getch();
}

请大家帮帮我!!

最佳答案

这是我的两个解决方案,它们非常简单粗暴。您可能需要改进。希望这可以帮助您入门。

  • 如果你只有少量的用户并且你需要经常检查用户帐户,你可以读入所有的用户名和密码,并将它们存储在一个std::map中,其中键是 username,值是 password

    假设usernamepassword存储在如下文件中(以空格分隔):

    user1 password1 user2 password2

    你可以像这样实现上面的想法:

    ifstream fin;
    fin.open("input.txt");
    map<string, string> m;
    while(!fin.eof())
    {
    string username, password;
    fin >> username >> password;
    m[username] = password; // store in a map
    }
    fin.close();
    // check account from user input
    string user, pwd;
    cin >> user >> pwd;
    if (m.find(user) != m.end())
    if (m[user] == pwd)
    // login
    else
    // wrong password
    else
    // reject
  • 如果用户数量较多,您可以将用户名和密码一一读入,并立即查看账户。

    while(!fin.eof())
    {
    string username, password;
    fin >> username >> password;
    if (username == user)
    {
    if (password == pwd)
    // login
    else
    // wrong password
    break;
    }
    }
    // didn't find user and reject

关于c++ - 检查用户是否存在(所有用户帐户都存储在一个文件中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17759930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com