strtoll 是一个C语言库函数,用于将字符串转换为长整型(long long)数值
stdlib.h 头文件以使用 strtoll 函数。#include <stdlib.h>声明变量:声明一个字符串变量和一个长整型变量来存储转换后的数值。const char *str = "123456789012345";long long num;使用 strtoll 函数进行转换:调用 strtoll 函数并传入字符串变量、一个指向字符的指针(用于存储处理过程中遇到的非数字字符的位置)以及要转换的数字的基数(例如,十进制为 10)。char *endptr;num = strtoll(str, &endptr, 10);检查转换结果:检查 endptr 是否指向字符串的末尾,以确定字符串是否完全由数字组成。如果不是,可能发生了错误或者字符串中包含非数字字符。if (endptr == str || *endptr != '\0') { printf("Invalid input: not a number.\n");} else { printf("The converted number is: %lld\n", num);}下面是一个完整的示例代码:
#include<stdio.h>#include <stdlib.h>int main() { const char *str = "123456789012345"; long long num; char *endptr; num = strtoll(str, &endptr, 10); if (endptr == str || *endptr != '\0') { printf("Invalid input: not a number.\n"); } else { printf("The converted number is: %lld\n", num); } return 0;}这段代码会将字符串 “123456789012345” 转换为长整型数值并输出。