strtoul, strtoull
|
定义于头文件
<stdlib.h>
|
||
|
unsigned
long
strtoul
(
const
char
*
str,
char
**
str_end,
int base ) ; |
(C99前) | |
|
unsigned
long
strtoul
(
const
char
*
restrict
str,
char
**
restrict
str_end,
int base ) ; |
(C99起) | |
|
unsigned
long
long
strtoull
(
const
char
*
restrict
str,
char
**
restrict
str_end,
int base ) ; |
(C99起) | |
将 str 所指向的字节字符串中的无符号整数值进行解析。
丢弃所有空白字符(通过调用
isspace
识别),直到找到第一个非空白字符,然后尽可能多地提取字符以构成有效的
base-n
(其中n=
base
)无符号整数表示形式,并将其转换为整数值。有效的无符号整数值由以下部分组成:
- (可选) 正负号
-
(可选)
表示八进制基数的前缀 (
0)(仅当基数为 8 或 0 时适用) -
(可选)
表示十六进制基数的前缀 (
0x或0X)(仅当基数为 16 或 0 时适用) - 数字序列
基数的有效取值范围为
{0, 2, 3, ..., 36}
。对于基数为
2
的整数,有效数字集为
{0, 1}
;对于基数为
3
的整数,有效数字集为
{0, 1, 2}
,依此类推。对于大于
10
的基数,有效数字包含字母字符,从基数为
11
的整数对应的
Aa
开始,直至基数为
36
的整数对应的
Zz
。字符的大小写将被忽略。
当前安装的 C locale 可能接受其他数字格式。
如果
base
的值为
0
,将自动检测数值进制:若前缀为
0
则为八进制,若前缀为
0x
或
0X
则为十六进制,否则为十进制。
如果减号是输入序列的一部分,则从数字序列计算得出的数值将被取反,如同通过结果类型中的 一元减号 操作,该操作遵循无符号整数回绕规则。
该函数将 str_end 所指向的指针设置为指向最后一个被解释字符之后的位置。如果 str_end 是空指针,则此参数将被忽略。
目录 |
参数
| str | - | 指向待解析的空终止字节字符串的指针 |
| str_end | - | 指向字符指针的指针,可被设置为最后一个已解析字符之后的位置 |
| base | - | 被解析整数值的 基数 |
返回值
成功时返回与
str
内容对应的整数值。若转换值超出对应返回类型的范围,则发生范围错误(
errno
被设为
ERANGE
)并返回
ULONG_MAX
或
ULLONG_MAX
。若无法执行任何转换,则返回
0
。
示例
#include <errno.h> #include <stdio.h> #include <stdlib.h> int main(void) { const char* p = "10 200000000000000000000000000000 30 -40 - 42"; printf("Parsing '%s':\n", p); char* end = NULL; for (unsigned long i = strtoul(p, &end, 10); p != end; i = strtoul(p, &end, 10)) { printf("'%.*s' -> ", (int)(end - p), p); p = end; if (errno == ERANGE) { errno = 0; printf("range error, got "); } printf("%lu\n", i); } printf("After the loop p points to '%s'\n", p); }
输出:
Parsing '10 200000000000000000000000000000 30 -40 - 42': '10' -> 10 ' 200000000000000000000000000000' -> range error, got 18446744073709551615 ' 30' -> 30 ' -40' -> 18446744073709551576 After the loop p points to ' - 42'
参考文献
- C23 标准 (ISO/IEC 9899:2024):
-
- 7.24.1.7 strtol、strtoll、strtoul 和 strtoull 函数 (页码: 待定)
- C17 标准 (ISO/IEC 9899:2018):
-
- 7.22.1.4 strtol、strtoll、strtoul 和 strtoull 函数 (页: 251-252)
- C11 标准 (ISO/IEC 9899:2011):
-
- 7.22.1.4 strtol、strtoll、strtoul 和 strtoull 函数 (页码: 344-345)
- C99标准(ISO/IEC 9899:1999):
-
- 7.20.1.4 strtol、strtoll、strtoul和strtoull函数(页码:310-311)
- C89/C90 标准 (ISO/IEC 9899:1990):
-
- 4.10.1.6 strtoul 函数
参见
|
(C95)
(C99)
|
将宽字符串转换为无符号整数值
(函数) |
|
(C99)
|
将字节字符串转换为整数值
(函数) |
|
(C99)
|
将字节字符串转换为整数值
(函数) |
|
C++ documentation
for
strtoul
|
|