c - 如何实现数据输入验证
问题描述
我想创建一个函数,以便它检查输入值的范围以及傻瓜保护,也就是说,如果该字段应该存储一个数值,那么用户就不能输入字符串值。这是我得到的功能:
void ENTER_DATA(struct DATA* notebook)
{
scanf("%s", notebook->surname);
scanf("%s", notebook->name);
scanf("%s", notebook->patronymic);
/*scanf("%u", ¬ebook->BirthDate);*/
notebook->BirthDate = CHECK("Enter your date of birth:\nDay ->");
scanf("%u", ¬ebook->BirthMonth);
scanf("%u", ¬ebook->BirthYear);
scanf("%s", notebook->addresSTREET);
scanf("%u", ¬ebook->addresHOME);
scanf("%u", ¬ebook->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
解决方案
问题是检查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);
...
}
推荐阅读
- laravel - 从 MessageBag Laravel 中删除自定义错误
- traefik - 如何暴露两个 HTTPS 端口?
- vue.js - 无法安装组件:未定义模板或渲染函数。(Vue 使用插件)
- python - Python写入抓取数据的json文件
- ruby - 如何为 Timecop 修补文件和核心扩展
- git - 在 VSTS 中搜索提交时产生错误:VCErrorCommitNotFound
- hive - cdh 到 hdp 配置单元
- javascript - 修改 D3 Force-Directed Graph 中的现有节点,而不会出现跳跃过渡
- batch-file - 有没有办法对 forfiles 执行否定搜索掩码?
- python - 如何在谷歌 colab 上执行搅拌机命令?