密码字段中显示额外的字母

Extra letter being displayed in Password Field

本文关键字:字段 显示 密码      更新时间:2023-10-16
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]='';       //inserting null char. at the end
     cout<<"n"<<newPassword;
}

在功能createAccount();中,用户输入char newUsername[20]char newPassword[20]。但是,要将密码显示为******,我实现了一种不同的输入newPassword方式。但是,当我尝试显示newPassword输出有一个额外的字母时,它神奇地出现在命令框中,而无需我输入任何内容。

输出

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

如果有人能帮助我,我将不胜感激。

一个问题可能是你混合了conio(getch(和iostream(cin(,它们可能不同步。尝试在程序开头添加以下行:

ios_base::sync_with_stdio ();

另外,您读取密码直到看到13,但是,如果我没记错的话,实际上在窗口中按 Enter 首先产生10,然后13,因此您可能需要检查两者作为停止条件。

i

循环结束时递增。解决此问题的最简单方法是将password初始化为零

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
}