|
发表于 2004-4-1 19:08:28
|
显示全部楼层
回去看了一下文档,发现在输入比较复杂的时候用 strtol 函数最好。
健壮 功能强大。
库:stdlib.h
原形:
long int strtol (const char *string, char **tailptr, int base)
参数:
1。 string: 输入的串
2。 tailptr:如果一个正确格式后面还带其他非法输入,则把非法部分的指针存储到 *tailptr. 例如 输入 -123gjir, 那么 *tailptr 存储指向字符串"gjir"
3. base: 基, 也就是进制。 如果为0, 那么表示 8 10 16 进制,输入
123 0xfe 0Xfe 0170 都能识别。 如果是其他,例如2,表示2进制数,可以从2-36
另外,这个函数不怕上溢和下溢,如果出错,会有相应返回,同时设置全局变量
errno.
原文:
long int strtol (const char *restrict string, char **restrict tailptr, int base) Function
The strtol ("string-to-long") function converts the initial part of string to a signed integer, which is returned as a value of type long int.
This function attempts to decompose string as follows:
A (possibly empty) sequence of whitespace characters. Which characters are whitespace is determined by the isspace function (see Classification of Characters). These are discarded.
An optional plus or minus sign (+ or -).
A nonempty sequence of digits in the radix specified by base.
If base is zero, decimal radix is assumed unless the series of digits begins with 0 (specifying octal radix), or 0x or 0X (specifying hexadecimal radix); in other words, the same syntax used for integer constants in C.
Otherwise base must have a value between 2 and 36. If base is 16, the digits may optionally be preceded by 0x or 0X. If base has no legal value the value returned is 0l and the global variable errno is set to EINVAL.
Any remaining characters in the string. If tailptr is not a null pointer, strtol stores a pointer to this tail in *tailptr.
If the string is empty, contains only whitespace, or does not contain an initial substring that has the expected syntax for an integer in the specified base, no conversion is performed. In this case, strtol returns a value of zero and the value stored in *tailptr is the value of string.
In a locale other than the standard "C" locale, this function may recognize additional implementation-dependent syntax.
If the string has valid syntax for an integer but the value is not representable because of overflow, strtol returns either LONG_MAX or LONG_MIN (see Range of Type), as appropriate for the sign of the value. It also sets errno to ERANGE to indicate there was overflow.
You should not check for errors by examining the return value of strtol, because the string might be a valid representation of 0l, LONG_MAX, or LONG_MIN. Instead, check whether tailptr points to what you expect after the number (e.g. '\0' if the string should end after the number). You also need to clear errno before the call and check it afterward, in case there was overflow.
来源: GNU.org |
|