【发布时间】:2017-05-18 13:47:31
【问题描述】:
我了解到永远不应该相信用户的输入。在处理之前检查它已成为一种习惯。我几乎总是使用这种类型的函数,并且经常想知道这两个版本之间是否存在差异。
这是我的检查功能的一个简单示例:
版本 1
int checkASCII(char c) // Here we check, print error and return if it succeeded or not
{
if (!isascii(c))
{
fprintf(stderr, "Error. Not an ASCII character.\n.");
return 1;
}
if (!isdigit(c))
{
fprintf(stderr, "Error. Not a number.\n.");
return 1;
}
// potentially more checks
return 0;
}
int printASCIINumber() // So that here we just have to verify the success
{
char c;
c = getc(stdin);
if (checkASCII(c))
putc(c, stdout);
else return 1;
return 0;
}
第 2 版
int checkASCII(char c) // Here we just check errors regardless of what failed
{
if (!isascii(c))
return 1;
if (!isdigit(c)
return 1;
... // potentially more checks
return 0;
}
int printASCIINumber() // And here we verify success and print a general error message
{
char c;
c = getc(stdin);
if (checkASCII(c))
putc(c, stdout);
else
{
fprintf(stderr, "Error. Please input an ASCII number.\n");
return 1;
}
return 0;
}
如果有任何目标需要改进,我也不反对。谢谢。
【问题讨论】:
-
是的,将所有
chars 更改为ints(所有这些函数都需要int)getc想要一个以捕获EOF,并且ctype 系列函数也一样. -
if (!checkASCII(c))? -
@BLUEPIXY 只检查失败,因为检查失败和成功都没用?
-
我的评论是它与它的意图相反。
-
关于可移植性的兴趣点:
isascii()不在标准库中,而是在 gcc 中的 BSD 扩展,并且在 POSIX 中。 The POSIX Standard 将isascii()标记为已过时,并声明此功能可能会从未来版本中删除。
标签: c validation input