DEV Community

Cover image for DILI #13: Logging off Holiday. Logging in Back to work.
DHDucky
DHDucky

Posted on

DILI #13: Logging off Holiday. Logging in Back to work.

As you can see, last week, I did not post anything and yes, based on the title of this blog, I was on holiday. But it is justifiable, because it's my country's Independence Day. But less on that and more on today's topic: Authentication, aka Login and Logout.

Image description

The library I'm going to use to help me with this is fstream, which can create files, write information to files, and read information from files. With this, I can create a login system which create a file that stores the registration. Then, the login system will check if the username and password entered by the user match the usernames and passwords in the file. If they do, the user will be logged in. Otherwise, the user will be prompted to enter their username and password again.

This code will create the file and open it to store the infomations and I can even designated the location and the name of the file:

ofstream file;
file.open("d:\\CODES AND STUFFS\\SnakeGame\\" + username + ".txt");
Enter fullscreen mode Exit fullscreen mode

And to store user's inputs into the file, it's similar to cin but with "file" keyword:

file << username << endl << password;
file.close();
Enter fullscreen mode Exit fullscreen mode

After, it just a matter of matching the file's data with user's login's input:

bool Login()
{
    string username, password, checkUN, checkPW;
    cout << "Enter username: "; cin >> username;
    cout << "Enter password: "; cin >> password;

    ifstream read("d:\\CODES AND STUFFS\\SnakeGame\\"  + username + ".txt");
    getline(read, checkUN);
    getline(read, checkPW);

    if(checkUN == username && checkPW == password){
        return true;
    }
    else return false;

}
Enter fullscreen mode Exit fullscreen mode

With this a simple authentication system is created. And the only left to do is add this to your desired project. Mine is my first game: Snakes. Check my GitHub.

With this, more can be done like a note-taking app that can save your data and can only be accessed by you given correct authentication. I might post a blog about this by the middle of next week as a replacement for the missed last week's blog.

As always, all advices about anything are welcome. See you in about 3-4 days!

REFERENCES:
GeeksforGeeks
Help with visualizing

Top comments (0)