C++ | Masked Password (Part 2)

Hello peeps! Lord Hypersonic greets you. Today I am presenting you with an updated version of my previous masked password program. I think this idea is unique and should be shared with you people.
So, in my previous program when the user type password, it just prints "@" but in this program, it will print random characters instead of printing "@".

The algorithm of the whole program is the same as the previous program just difference is in the print section. CLICK HERE TO SEE THE PREVIOUS VERSION OF THE PROGRAM.
So we just have to generate random numbers between 32 to 126, because according to ASCII table printable characters begin from 32 to 126. After that, we just have to assign that number to a character variable.
After that, we add the value of that character variable at the end of the string which you are using to print "@" or "*" or any other symbol.

Source Code:-

/*
Program: masked password
Description: To hide the password/ input and display @ in place of the character inputted.
Author: Lord Hypersonic
Email: lordhypersonic.522@gmail.com
Website: www.lordhypersonic.blogspot.com
*/
#include <iostream>
#include <string>
#include <conio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

string masked_input()
{
    srand(time(0));
    string Minput,print;
    char input;
    cout<<"Enter password: ";
    input = _getch();
    while (input != 13) // continue till user press RETURN/ENTER Key
    {
        if (input == 8) // if user press backspace key
        {
            if (print.size() == 0) // if length of Minput is zero
            {
                print = ""; //make print equal to empty string
                Minput = ""; //make Minput equal to empty string
            }
            else //if length of Minput/print is not zero or greater than zero
            {
                print.resize(print.size()-1); //resize print to its length - 1
                cout<<print; // print value of print
                Minput.resize(Minput.size()-1); // resize Minput string to its length - 1
            }
        }
        else // if user do not press backspace key.
        {
            char c = (rand()%126)+32;
            print.push_back(c); //add value of "c" at end of print
            cout<<print; //print value of print
            Minput.push_back(input); //add the key pressed at the end of Minput string
        }
        input = _getch(); //ask user for input / press keys
        system("cls"); //clear screen
        cout<<"Enter password: ";
    }
    return Minput;
}

int main()
{
    string password = masked_input();

    if (password == "m@$k3d p@$$w0rd") //if password entered is correct
    {
        cout<<endl<<"Welcome back my friend"<<endl; //print this
    }
    else  //if password is not correct
    {
        cout<<endl<<"Incorrect password........... Can't let you in"<<endl; //print this
    }
    return 0;
}


No comments

Powered by Blogger.