Read the text file for login authentication using a delimiter;

I have a problem reading a file using delimeter; read and compare password and username. Currently, my code only allows me one username and one password, each in a separate text file.

I would like my text file to be in this format, and the function will check the text file line by line, and each username and password are separated by a ";"

user;pass user2;pass2 user3;pass3 

Here is my current code.

 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
source share
2 answers

You can use getline for this:

 #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); } 
+4
source

Several parameters:

  • std::getline accepts a terminator, so you can use ';' as a terminator for your getline after the name, and not for the usual '\n'

  • Read the line in std::string (using getline or even >> ), then use std::string::find to find the half-time, and then you can use std::string::substr() to highlight the name and password.

  • regex or the like, but probably not quite what you want here.

As you pointed out a format that seems to be all stored in one file.

You can either

  • Download the entire file and save std::map< std::string, std::string > , then check the user login.

  • Since you will only have one login, you read the file after the person has entered his username (and password), line at a time, until you find the one that matches the one they entered.

+2
source

Source: https://habr.com/ru/post/1441542/


All Articles