我正在用 c 编写一个程序,它在命令行上接受用户的参数,但该参数必须是有效的无符号整数。例如,如果用户输入值-1,那么我将不得不打印错误代码。或者,如果用户输入高于 4294967295 的任何内容,那么我也会打印错误代码。
我不确定如何检查他们的输入是否在正确的范围内(0 和 4294967295)。
验证用户输入的数字实际上是 c 中有效的无符号整数
strtoul()
是正确使用的函数。它在接受时会带来一些问题'-'
。让我们假设前导空格是可以的,并手动检查字符串的前端。
// 0: invalid, 1: valid
int unsigned_int_valid(const char *s) {
while (isspace((unsigned char) *s) s++;
// Fail on '-' as any negative number is out of range.
if (*s == '-') return 0; // Could add code to allow "-0"
if (*s == '+') s++;
if (!isdigit((unsigned char) *s) return 0;
// Code knowns string begins with a digit
errno = 0; // Clear this global value as code tests it later.
char *endptr; // Pointer where parsing stopped.
unsigned long ul = strtoul(s, &endptr, 0);
// Usually this test is needed to see if _any_ conversion happened,
// but code knowns the first character is a digit.
#if 0
if (s == endptr) return 0;
#endif
// Could march down the end of the string allowing trailing white-space
while (isspace((unsigned char) *endptr) endptr++;
// Extra text after the digits?
if (*endptr) return 0;
// Overflow? strtoul sets `errno = ERANGE` when "outside the range" of unsigned long
if (errno) return 0;
#if ULONG_MAX > UINT_MAX
// Does 'ul` value exceeds `unsigned` range?
if (ul > UINT_MAX) return 0;
#endif
return 1;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)