如何使用isdigit()进行引脚while

时间:2016-07-26 23:16:11

标签: c

这个程序接受任何四位数作为引脚,所以我使用strlen()来确定引脚是否有四个字符,但我需要确保用户输入四个数字,我该如何使用循环前的isdigit()和循环条件?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char pin [4];

printf("Please enter your pin :    \n") ;
scanf("%4s" , &pin) ;
system("cls") ;

while (strlen(pin) != 4) {
    count = count + 1 ;
    if(count < 3){
        printf("Invalid Pin \n") ;
        printf("Please enter your pin again \n") ;
        scanf("%4s", &pin) ;
        system("cls");
    }
    else if (count == 3){
        printf("Sorry you can't continue , Please contact your bank for assistance !") ;
        return 0 ;
    }
}

3 个答案:

答案 0 :(得分:2)

这段代码存在很多问题,我可能没有在这个答案中涵盖每一个问题:

  1. 您的主要功能在哪里?你不能在函数之外拥有代码;那不起作用。除了全局变量声明,常量值赋值,typedef,struct和enum定义之外的C代码,必须包含在函数中。在您的情况下,您可能希望main函数容纳从第6行开始的代码。

  2. 使用字符串参数调用scanf时,请不要使用字符串的地址 - 数组本身就是一个引用。

  3. 在将任何值复制到strlen(pin)之前调用pin是100%未定义的行为。由于内存未初始化,strlen函数将继续查找空字符,并可能超出数组边界。

  4. C字符串以空值终止。声明用于保存 n 字符的字符串时,需要声明大小为 n + 1 的数组,以便为​​空字符留出空间。

答案 1 :(得分:0)

首先回答你的问题

我会写一个帮助函数&#39; validatePin&#39;这将检查引脚长度并验证引脚是否为数字引脚,您可以扩展此功能以执行您需要的任何其他验证。它可能看起来像下面的

const int PIN_OK = 0;
const int PIN_INVALID_LEN = -1;
const int PIN_INVALID_CHARS = -2;

int validatePin(const char *pin)
{
    // Valdiate PIN length
    if (strlen(pin) != 4) return PIN_INVALID_LEN;

    // Validate PIN is numeric
    for (int i = 0; i < 4; ++i)
    {
        if (!isdigit(pin[i])) return PIN_INVALID_CHARS;
    }
    return PIN_OK;
}

然后你可以调整你的while循环看起来像下面的

while (validatePin(pin) != PIN_OK)
{
    ....   
}

有关您的代码的其他要点。

  • 用于scanf的char缓冲区不考虑null终止符。您需要增加缓冲区大小。
  • char数组已经为你提供了缓冲区的地址,没有必要使用&amp;获取scanf中char数组的地址。

我没有运行您的代码,因此可能还有其他问题乍一看我错过了。

答案 2 :(得分:0)

有很多方法可以做你需要做的事情。您既可以检查输入长度,也可以只选择验证您已阅读的内容。一种方法是:

#include <stdio.h>
#include <ctype.h>

enum { TRIES = 3, NPIN };

int main (void) {

    char pin[NPIN+1] = "";
    size_t tries = 0, pinok = 0;

    for (; tries < TRIES; tries++) {            /* 3 tries */
        printf ("Please enter your pin : ");
        if (scanf (" %4[^\n]%*c", pin) == 1) {  /* read pin */
            pinok = 1;
            size_t i;
            for (i = 0; i < NPIN; i++)  /* validate all digits */
                if (!isdigit (pin[i]))
                    pinok = 0;
            if (pinok)                  /* if pin good, break */
                break;
        }
    }

    if (!pinok) {   /* if here and not OK, call bank */
        fprintf (stderr, "Sorry you can't continue, Please contact "
                        "your bank for assistance.\n") ;
        return 1;
    }

    printf ("\n correct pin : %s\n\n", pin);    /* your pin */

    return 0;
}

注意:以防止一次输入过长的字符串,您应该在每次迭代的外部stdin循环结束时清空for

示例使用/输出

案例失败:

$ ./bin/pin
Please enter your pin : a555
Please enter your pin : 555a
Please enter your pin : 55a5
Sorry you can't continue , Please contact your bank for assistance.

成功案例:

$ ./bin/pin
Please enter your pin : 2345

 correct pin : 2345

看看它,如果您有任何问题,请告诉我。

相关问题