【问题标题】:c program to check the user entered pin with the already set 4 digit pinc程序用已经设置的4位密码检查用户输入的密码
【发布时间】: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


【解决方案1】:

试试这个以获取只有数字作为输入 -

int count = 0;
while(count<4){
    scanf(" %c", &ch);
    if(ch>='0' && ch<='9'){
        count++;
    }
}

【讨论】:

  • 与 getch scanf 不同,它将等待输入整行并回显字符。此外,您没有保存输入的字符。
  • @stark buddy 感谢您在 scanf 的情况下纠正我,以及关于存储字符我只是给他检查条件的线索,尽管存储字符可以在数组的帮助下完成 :-)
【解决方案2】:

输入一个 4 位数的 Pin 并检查它是否正确。

使用fgets()读取一行用户输入

char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
  buf[strcspn(buf, "\n")] = 0; // Lop off potential trailing \n

测试输入并累积pin

  // to ignore all the other characters except numbers and 
  // also i just want the user to enter exactly 4 digits.
  unsigned pin = 0;
  size_t count = 0;
  for (char *s = buf; *s; s++) {
    if (*s >= '0' && *s <= '9') {
      pin = pin * 10 + *s - '0';
      count++;
    }
  }
  success = count == 4;

IMO,最好不要忽略其他人,只允许数字

  unsigned pin = 0;
  size_t count = 0;
  for (char *s = buf; *s >= '0' && *s <= '9'; s++) {
    pin = pin * 10 + *s - '0';
    count++;
  }
  success = *s == '\0' && count == 4;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 2015-03-25
    • 2016-06-28
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多