【问题标题】:Extra letter being displayed in Password Field密码字段中显示的额外字母
【发布时间】:2015-11-17 21:01:19
【问题描述】:
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;
}

在函数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&lt;10, newPassword[i]!=8是可疑的。
  • 我相信您看到的额外 * 是空白字符。如果您尝试检查 newPassword 数组,您得到的实际字符是什么?
  • 我会将退格检查移到循环中,以便阅读清晰。 for(i=0;i
  • 逗号应该改成&amp;&amp;。见:Comma Operator in Conditon of Loop in C

标签: c++ borland-c++


【解决方案1】:

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

ios_base::sync_with_stdio ();

此外,您在看到 13 之前读取密码,但是,如果我没记错的话,实际上在 Windows 中按 Enter 会首先生成 10,然后是 13,因此您可能需要同时检查两者停止条件。

【讨论】:

    【解决方案2】:

    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
    }
    

    【讨论】:

    • 1) 如果按,则不会执行最后一个增量。 break 立即跳出循环。 2) 在示例输出中,违规字符位于字符串的开头。
    • 谢谢@JohnnyMopp,我想我现在修好了,我应该远离这个:)
    • @BarmakShemirani 似乎已经做到了。谢谢! :)
    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 2018-09-25
    • 2015-11-20
    • 2023-03-25
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    相关资源
    最近更新 更多