3

我正在编写一个代码来接收密码输入。下面是我的代码...程序运行良好,但问题是除了数字和字母字符之外的其他键也被读取,例如删除、插入等。我可以知道如何避免它吗?咳咳……

string pw="";
char c=' ';

while(c != 13) //Loop until 'Enter' is pressed
{
    c = _getch();
    if(c==13)
        break;

    if(c==8)
    {
        if(pw.size()!=0)   //delete only if there is input 
        {
            cout<<"\b \b";
            pw.erase(pw.size()-1);
        }
    }

    if((c>47&&c<58)||(c>64&&c<91)||(c>96&&c<123))  //ASCii code for integer and alphabet
    {
        pw += c;
        cout << "*";
    }
}
4

2 回答 2

7

过滤使用isalnum()字母数字或isalpha()仅字母。

另外,您要检查c == 13两次,以下就足够了。

while(1){
  //
  if(c == 13)
    break;
  //
}

if( isalnum(c) ){
  // 'c' is acceptable
}

某些断言在执行期间失败,从而引发该错误。

于 2010-03-26T11:18:11.263 回答
2

如果你可以访问它,你最好使用 GNUgetpass函数。

于 2010-03-26T11:21:26.293 回答