Firs of all hello guys.And then straight to the point :) Ok so my trouble is with creating a password function that will display '*' instead of normal chars.So here is my code:

string EnterPass()
{
    string Pass="";
    char ch=getch();
    while (ch != '\r') 
    {
        if(ch=='\b')
        cout<<'\b'<<' '<<'\b';
        else
        {
        cout << '*';
        Pass += ch;
        }
        ch=getch();
        
    }
    return Pass;
}

bool Access()
{
     string password=EnterPass();
     if(password=="zerozone") return true;
     else return false;
}

The first problem I came onto was that the program didn't handel backspaces and displayed them as '*' as well ,but i fixed that. Now the program displayes the backspaces right but it adds the to the string Pass and then adds the next letter I type resulting wrong password.
if I type "zerr" then "\b" and then "ozone" it results in "zerr\bozone". Please help .Any assistance will be appreciated.

How about changing this:

if (ch=='\b')
     cout<<'\b'<<' '<<'\b';

to this:

if (ch=='\b')
{
     cout<<'\b'<<' '<<'\b';
     Pass.resize (Pass.length () - 1);
}

You'd have to add code to make sure that you can't backspace on the empty string but it works otherwise as far as I have tested it.

Thanks mate.You saved me hours.I am surprised that the answer is so simple :).Thank you very much,it really works :)

i had the same issue using the same code. im using dev C++ and if i use the backspace and go beyond the beginning of the entered password the program crashes. does anyone have a similiar problem

This question has already been answered. Start a new discussion instead.