4

我有一个如何使用分隔符读取文件的问题;读取和比较密码和用户名。目前我的代码只允许我读取一个用户名和一个密码,每个都在一个单独的文本文件中。

我希望我的文本文件采用这种格式,并且该函数将逐行检查文本文件,每个用户名和密码用“;”分隔

user;pass
user2;pass2
user3;pass3

这是我当前的代码。

void Auth()
{
     ifstream Passfile("password.txt", ios::in);
     Passfile>>inpass;
     ifstream Userfile("username.txt", ios::in);
     Userfile>>inuser;
     //system("clear");
     cout<<"USERNAME: ";
     cin>>user;
     cout<<"PASSWORD: ";
     cin>>pass;
     Userfile.close();
     Passfile.close();
     if(user==inuser&&pass==inpass)
     {
     cout<<"\nLogin Success!!\n";
     cin.get();
     Members();
     }
     else
     {
        cout<<"\nLogin Failed!!\n";
         main();
     }
}
4

2 回答 2

4

你可以使用getline,就像这样:

#include <iostream>
#include <fstream>
#include <string>

bool authenticate(const std::string &username, const std::string &password) {
    std::ifstream file("authdata.txt");
    std::string fusername, fpassword;

    while (file) {
        std::getline(file, fusername, ';'); // use ; as delimiter
        std::getline(file, fpassword); // use line end as delimiter
        // remember - delimiter readed from input but not added to output
        if (fusername == username && fpassword == password)
            return true;
    }

    return false;
}

int main() {
    std::string username, password;
    std::cin >> username >> password;
    return (int)authenticate(username, password);
}
于 2012-10-23T13:04:37.963 回答
2

几个选项:

  1. std::getline需要一个终止符,因此您可以';'在名称之后用作 getline 的终止符,而不是常规'\n'

  2. 将一行读入a std::string(使用getline或什至>>),然后使用std::string::find查找分号,然后您可以使用std::string::substr()分隔名称和密码。

  3. 正则表达式或类似的,但可能不是你真正想要的。

您指定格式的方式似乎全部存储在一个文件中。

你可以

  1. 加载整个文件,然后存储std::map< std::string, std::string >然后检查用户登录。

  2. 由于您只会登录一次,因此您在此人输入用户名(和密码)后读取文件,一次一行,直到找到与他们输入的匹配的文件。

于 2012-10-23T12:28:56.633 回答