Search code examples
c++borland-c++

Extra letter being displayed in Password Field


void createAccount(){

        int i=0;
        cout<<"\nEnter new Username: ";
        cin.ignore(80, '\n');
        cin.getline(newUsername,20);
        cout<<"\nEnter new Password: ";

        for(i=0;i<10,newPassword[i]!=8;i++){

            newPassword[i]=getch();    //for taking a char. in array-'newPassword' at i'th place
            if(newPassword[i]==13)     //checking if user press's enter
                break;                 //breaking the loop if enter is pressed
            cout<<"*";                 //as there is no char. on screen we print '*'
        }

     newPassword[i]='\0';       //inserting null char. at the end

     cout<<"\n"<<newPassword;
}

In function createAccount(); the user is entering char newUsername[20] and char newPassword[20]. However, to display the password as ****** I've implemented a different way for entering newPassword. However, when I try displaying newPassword the output has an extra letter that magically appears in the command box without me entering anything.

OUTPUT

Enter new Username: anzam
Enter new Password: ****** //entered azeez but the first * is already there in command box without user inputting anything

Mazeez //displaying newPassword

If someone could help me I'd be extremely grateful.


Solution

  • i has been incremented at the end of the loop. The easiest way to fix this is to initialize password to zero

    char newPassword[20];
    memset(newPassword, 0, 20);
    
    for (i = 0; i < 10; )
    {
        int c = getch();
        if (c == 13)
            break;
    
        //check if character is valid
        if (c < ' ') continue;
        if (c > '~') continue;
    
        newPassword[i] = c;
        cout << "*";
        i++; //increment here
    }