因此,我必须使用密码对控制台应用程序进行加密,我做了一些有效的操作,但是有一个问题,后退键不会擦除输入的字符,它也被算作字符,我该怎么做呢?做它的工作,以消除角色?
这是代码:
void main()
{
char password[20], my_password[20] = "password";
int i;
char ch;
system("cls");
cout << "PASSWORD: ";
i = 0;
do
{
ch = _getch();
password[i] = ch;
if (ch != 27 && ch != 13 && ch != 9)
cout<<"*";
else
break;
i++;
} while (i < 19);
password[i] = '\0';
if (strcmp(password, my_password) != 0)
{
cout << "\n\nIncorrect password !!!";
cin.get();
return;
}
cout << "\n\nPassword is correct !";
cout <<"\n\nThe program is executed !";
cin.get();
}
答案 0 :(得分:1)
“我该如何做才能消除角色?”
使用Owner
库。像ncurses。
答案 1 :(得分:1)
您可以检查接收到的字符是否为退格键,减量i
是否可以有效删除最后一个字符。
i = 0;
do
{
ch = _getch(); // get the character
if(ch == DEL || ch == BS) // check for backspace
{
i--;
cout << BS;
}
else if(ch >= ' ' && ch <= '~') // check if its valid ASCII
{
password[i] = ch;
cout << "*";
i++;
}
else if (ch == 27 || ch == 13 || ch == 9) // check if entry is complete
{
break;
}
} while (i < 19);
password[i] = '\0';
其他地方
#define BS '\b'
#define DEL 127
答案 2 :(得分:1)
void main()
{
char password[20], my_password[20] = "password";
int i;
char ch;
system("cls");
cout << "PASSWORD: ";
i = 0;
do
{
ch = _getch();
if (ch == 8)
{
i--;
cout << "\b \b";
continue;
}
password[i] = ch;
if (ch != 27 && ch != 13 && ch != 9)
cout << "*";
else
break;
i++;
} while (i < 19);
password[i] = '\0';
if (strcmp(password, my_password) != 0)
{
cout << "\n\nIncorrect password !!!";
cin.get();
return;
}
cout << "\n\nPassword is correct !";
cout << "\n\nThe program is executed !";
cin.get();
}
不是最干净的代码,但是它可以工作。减少计数器以覆盖前一个字符,并输出两个由空格分隔的退格字符。