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

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]='[=10=]';       //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

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

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
}

一个问题可能是您混合了 conio (getch) 和 iostream (cin),并且它们可能不同步。尝试在程序的开头添加这一行:

ios_base::sync_with_stdio ();

此外,您阅读密码直到看到 13,但是,如果我没记错的话,实际上在 windows 中按 enter 会先生成 10,然后生成 13,因此您可能希望将两者都检查为停止条件。