首页 > 解决方案 > 如何实现数据输入验证

问题描述

我想创建一个函数,以便它检查输入值的范围以及傻瓜保护,也就是说,如果该字段应该存储一个数值,那么用户就不能输入字符串值。这是我得到的功能:

void ENTER_DATA(struct DATA* notebook)
{
    scanf("%s", notebook->surname);
    scanf("%s", notebook->name);
    scanf("%s", notebook->patronymic);
    /*scanf("%u", &notebook->BirthDate);*/
    notebook->BirthDate = CHECK("Enter your date of birth:\nDay ->");
    scanf("%u", &notebook->BirthMonth);
    scanf("%u", &notebook->BirthYear);
    scanf("%s", notebook->addresSTREET);
    scanf("%u", &notebook->addresHOME);
    scanf("%u", &notebook->mobileNUMBER);
}

这里是调用它的地方:

int CHECK(const char* msg)
{
    char userGetLine[256]; //string to read
    unsigned int user_number; //total number

    while (getchar() != '\n');
    printf("%s", msg);
    fgets(userGetLine, sizeof(userGetLine), stdin); //reading the string

    while (sscanf(userGetLine, "%u", &user_number) != 1 )
    {
        printf("Error. Try again\n-> "); // we display an error message
        fgets(userGetLine, sizeof(userGetLine), stdin); // and re-read the string
    }
    return user_number;
}

运行代码时出现错误:Debug Assertion Failed! 请帮我完成它,我不知道问题是什么(在这里我扔掉了整个程序 - https://ideone.com/3mC4fy

标签: c

解决方案


问题是检查CHECK中的范围,应该这样检查: while (scanf("%d", &user_number) != 1 || user_number < a || user_number > b ) 也不清楚为什么要将user_number传递给CHECK,它的值没有被使用,并且scanf覆盖了它。CHECK 要求您重复输入,直到输入正确的值,然后返回。但是调用代码忽略了这个值。不需要 getchar 循环。有必要像这样重写检查:

nt CHECK(int a, int b)
{
    int user_number;
    while (scanf("%d", &user_number) != 1 ||  user_number < a || user_number > b )
    {
            printf("Error. Try again\n-> ");
    }
    return user_number;
}

void ENTER_DATA(struct DATA* notebook)
{
...
notebook->BirthDate = CHECK(1,31);
...
}

推荐阅读