C

strtol

strtol, strtoll

在头文件中定义
long strtol(const char * str,char ** str_end,int base);(直到C99)
long strtol(const char * restrict str,char ** restrict str_end,int base);(自C99以来)
long long strtoll(const char * restrict str,char ** restrict str_end,int base);(自C99以来)

解释str指向的字节字符串中的整数值。

放弃任何空格字符(通过调用标识isspace()),直到找到第一个非空白字符,然后接收尽可能多的字符以形成有效的base-n(其中n = base)整数表示并将它们转换为整数值。有效的整数值由以下部分组成:

  • (可选)加号或减号

base的有效值集合是{0,2,3,...,36}。base-2整数的有效数字集合是{0,1},对于base-3整数是{0,1,2},依此类推。对于大于等于的基数10,有效数字包含字母字符,从Aa基数为11的整数开始,到Zz基数为36的整数。字符的情况被忽略。

其他数字格式可以被当前安装的C语言环境接受。

如果基数的值是​0​,数字基地是自动检测:如果前缀是0,基地是八进制的,如果前缀是0x0X,基地是十六进制,否则基数是十进制。

如果减号是输入序列的一部分,则根据数字序列计算的数值将被否定,如同在结果类型中使用一元减号一样。

这些函数将str_end指向的指针设置为指向经过最后解释的字符的字符。 如果str_end是NULL,它将被忽略。

如果str为空或者没有预期的形式,则不执行转换,并且(如果str_end不是NULL),则str的值将存储在str_end指向的对象中。

参数

str-指向要解释的以空字符结尾的字节字符串
str_end-指向字符的指针。
base-解释的整数值的基数

返回值

  • 如果成功,str则返回与内容相对应的整数值。

#include <stdio.h> #include <errno.h> #include <stdlib.h> int main(void) { // parsing with error handling const char *p = "10 200000000000000000000000000000 30 -40 junk"; printf("Parsing '%s':\n", p char *end; for (long i = strtol(p, &end, 10 p != end; i = strtol(p, &end, 10)) { printf("'%.*s' -> ", (int)(end-p), p p = end; if (errno == ERANGE){ printf("range error, got " errno = 0; } printf("%ld\n", i } // parsing without error handling printf("\"1010\" in binary --> %ld\n", strtol("1010",NULL,2) printf("\"12\" in octal --> %ld\n", strtol("12",NULL,8) printf("\"A\" in hex --> %ld\n", strtol("A",NULL,16) printf("\"junk\" in base-36 --> %ld\n", strtol("junk",NULL,36) printf("\"012\" in auto-detected base --> %ld\n", strtol("012",NULL,0) printf("\"0xA\" in auto-detected base --> %ld\n", strtol("0xA",NULL,0) printf("\"junk\" in auto-detected base --> %ld\n", strtol("junk",NULL,0) }

输出:

Parsing '10 200000000000000000000000000000 30 -40 junk': '10' -> 10 ' 200000000000000000000000000000' -> range error, got 9223372036854775807 ' 30' -> 30 ' -40' -> -40 "1010" in binary --> 10 "12" in octal --> 10 "A" in hex --> 10 "junk" in base-36 --> 926192 "012" in auto-detected base --> 10 "0xA" in auto-detected base --> 10 "junk" in auto-detected base --> 0

参考

  • C11标准(ISO / IEC 9899:2011):

扩展内容

atoiatolatoll(C99)将字节字符串转换为整数值(函数)
strtoul strtoull(C99)将字节字符串转换为无符号整数值(函数)
wcstolwcstoll(C95)(C99)将宽字符串转换为整数值(函数)
wcstoulwcstoull(C95)(C99)将宽字符串转换为无符号整数值(函数)

| strtol,strtoll的C ++文档 |