strtoul
函数 <cstdlib>
unsigned long int strtoul (const char* str, char** endptr, int base);
将字符串转换为 unsigned long integer
解析C-string str,将其内容解释为指定base(进制)的整数值,返回unsigned long int类型的值。
这个函数类似于
strtol来解释字符串,但会产生unsigned long int类型的数字
(有关解释过程的详细信息,请参阅
strtol)。
☲ 参数
str
以整数表示开头的c字符串。
endptr
对已经分配的char*类型对象的引用,该对象的值由函数设置为数值后的str中的下一个字符。
这个参数也可以是一个空指针,在这种情况下它不会被使用。
base
确定有效字符及其解释的基数(radix)。
如果该值为0,则使用的基数由序列中的格式决定(详情请参阅
strtol)。
☉ 返回值
如果成功,该函数将转换后的整数值作为 unsigned long int型值返回。
如果不能执行有效的转换,则返回零值。
如果读的值超出了unsigned long int的可表示值范围,则函数返回ULONG_MAX
(在<
climits>中定义),
errno设置为ERANGE。
☣ 示例
/* strtoul example */
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* strtoul */
int main ()
{
char buffer [256];
unsigned long ul;
printf ("Enter an unsigned number: ");
fgets (buffer, 256, stdin);
ul = strtoul (buffer, NULL, 0);
printf ("Value entered: %lu. Its double: %lu\n",ul,ul*2);
return 0;
}
|
可能输出:
Enter an unsigned number: 30003
Value entered: 30003. Its double: 60006
↭ 数据竞争
str指向的数组被访问,endptr指向的指针被修改(如果不是null)。
❆ 异常(c++)
无抛出保证:此函数从不抛出异常。
如果str没有指向有效的C-string,或者endptr没有指向有效的指针对象,将导致未定义的行为。
🍄 另请参阅
strtod |
将string转换为double (function) |
strtof |
将string转换为float (function) |
strtol |
将string转换为long integer(function) |
atol |
将字符串转换为 long integer (function ) |