用c语言写一个数字密码锁,它包含以下功能:①能够在显示屏上显示数字键盘②用户按下不同按键时,有不同的处理:0~9输入密码,*确认,#删除一位密码,0#0*更改密码③在空白地方显示输入密码的位数④每一个按键拥有按下效果⑤按下*确认时,会将用户输入的密码和内置密码进行对比,在显示屏上显示结果
时间: 2024-04-07 07:33:21 浏览: 17
下面是一个用C语言编写的数字密码锁的例代码:
```c
#include <stdio.h>
#includestdlib.h>
#include <string.h>
#define MAX_LENGTH 4
#define PASSWORD "123"
void displayKeypad printf("Please enter the password:\n");
printf("0 1 2\n");
printf("3 4 5\n");
printf("6 7 8\n");
printf("9 * #\n");
}
void handleInput(char input, char* password, int* passwordLength) {
switch(input) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (*passwordLength < MAX_PASSWORD_LENGTH) {
password[*passwordLength] = input;
(*passwordLength)++;
printf("Password length: %d\n", *passwordLength);
}
break;
case '#':
if (*passwordLength > 0) {
(*passwordLength)--;
printf("Password length: %d\n", *passwordLength);
}
break;
case '*':
if (*passwordLength == MAX_PASSWORD_LENGTH) {
if (strcmp(password, PASSWORD) == 0) {
printf("Password correct!\n");
} else {
printf("Password incorrect!\n");
}
memset(password, 0, sizeof(password));
*passwordLength = 0;
} else {
printf("Invalid password length!\n");
}
break;
default:
printf("Invalid input!\n");
break;
}
}
int main() {
char password[MAX_PASSWORD_LENGTH];
int passwordLength = 0;
char input;
displayKeypad();
while (1) {
scanf(" %c", &input);
handleInput(input, password, &passwordLength);
}
return 0;
}
```
这个代码实现了一个简单的数字密码锁。用户按下不同的按键时,根据按键的不同执行不同的处理逻辑。在空白地方显示输入密码的位数,按下*确认时,会将用户输入的密码与内置密码进行对比,并在显示屏上显示结果。你可以根据需要进行修改和扩展。