【发布时间】:2021-10-09 06:04:37
【问题描述】:
输入一个 4 位数的 Pin 并检查是否正确。
该程序用 * 掩盖了 4 位数字,但我遇到的问题是我想忽略除数字以外的所有其他字符,而且我只想让用户准确输入 4 位数字。
希望你们能理解我的代码
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define TAB 9
#define BKSP 8
#define SPACE 32
void main(){
int pin = 1234 ;
char apin[4] , ch;
int attempt ;
int i;
int pw = 0;
for(attempt=1; attempt<=3; attempt++) {
printf("Enter 4 digit pin code:\n");
for(i=0;i<4;i++)
{
ch = getch();
if(ch == BKSP)
{
if(i>0){
i--;
printf("\b \b");
}
}
else if(ch==TAB || ch == SPACE ){
continue;
}
else{
apin[i] = ch;
ch = '*' ;
printf("%c",ch);
}
}
apin[i] = ' ';
printf("\n");
pw = atoi(apin) ;
//printf("%d\n",pw);//
if(pw != 1234){
printf("Invalid Pin\n");
printf("You have %d attempts remaining\n",3-attempt);
}
else{
printf("Your have entered the correct pin code\n");
break;
}
}
}```
【问题讨论】:
-
"我想忽略除数字以外的所有其他字符" - 为什么?这会提供您可能不希望入侵者拥有的潜在入侵者信息。
-
循环之后,
apin[i] = ' ';超出了数组边界,并且char apin[4]无论如何都不能是atoi()所需的以 NUL 结尾的字符串。 -
你有什么问题?
-
“您已进入”应为“您已进入”
-
pw = atoi(apin) ;将验证输入,例如"+1234"。
标签: c for-loop if-statement