CppDS.com

C++ 98 11 14 17 20 手册

strtoul, strtoull

来自cppreference.com
< c‎ | string‎ | byte
定义于头文件 <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() 鉴别),直到找到首个非空白符,然后取尽可能多的字符组成底 n (其中 n=base )的无符号整数表示,并将它们转换成一个整数值。合法的无符号整数值由下列部分组成:

  • (可选)正或负号
  • (可选)指示八进制底的前缀( 0 )(仅当底为 80 时应用)
  • (可选)指示十六进制底的前缀( 0x0X )(仅当底为 160 时应用)
  • 一个数字序列

底的合法集是 {0,2,3,...,36} 。合法数字集对于底 2 整数是 {0,1},对于底3整数是 {0,1,2} ,以此类推。对于大于 10 的底,合法数字包含字母字符,从对于底 11 整数的 Aa 到对于底36整数的 Zz 。忽略字符大小写。

当前安装的 C 本地环境可能接受另外的数字格式。

若 base 为 0 ,则自动检测数值进制:若前缀为 0 ,则底为八进制,若前缀为 0x0X ,则底为十六进制,否则底为十进制。

若符号是输入序列的一部分,则对从数字序列计算得来的数字值取反,如同用结果类型的一元减,它对无符号整数应用回卷规则。

函数设置 str_end 所指向的指针指向最后一个被转译字符的后一字符。若 str_end 为空指针,则忽略它。

参数

str - 指向要被转译的空终止字符串的指针
str_end - 指向指向字符的指针的指针。
base - 被转译整数值的

返回值

成功时为对应 str 内容的整数值。若被转换值落在对应返回类型的范围外,则发生值域错误( errno 被设为 ERANGE )并返回 ULONG_MAXULLONG_MAX 。若无转换可进行,则返回 0

示例

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
 
int main(void)
{
    const char *p = "10 200000000000000000000000000000 30 -40";
    printf("Parsing '%s':\n", p);
    char *end;
    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){
            printf("range error, got ");
            errno = 0;
        }
        printf("%lu\n", i);
    }
}

输出:

Parsing '10 200000000000000000000000000000 30 -40':
'10' -> 10
' 200000000000000000000000000000' -> range error, got 18446744073709551615
' 30' -> 30
' -40' -> 18446744073709551576

引用

  • C11 standard (ISO/IEC 9899:2011):
  • 7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 344-345)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions (p: 310-311)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.10.1.6 The strtoul function

参阅

将宽字符串转换成无符号整数值
(函数)
将字节字符串转换成整数值
(函数)
将字节字符串转换成整数值
(函数)
关闭