在 C 中将大串数字(14 位)转换为整数或长整数
Converting large string of numbers (14 digits) to integer or long in C
我有一个包含 14 位数字的字符串。
我想将字符串转换为整数。
当我使用 atoi(stringName) 时,我得到了最大 32 位的限制。
示例:
String1 包含“201400000000”
long long tempNum1;
tempNum1 = atoi(String1);
printf("%d",tempNum1);
输出为:2147483647
如何将此字符串转换为数字?我想将它与其他数字串进行比较,找出最大的一个。 (我有3串14位数字,想求哪个最小,哪个最大)
atoi
returns 一个 int
.
那个int
分配给了一个long long
,但是到那时已经达到了限制。
您想使用 atoll
其中 returns 一个 long long
。
并且您的 printf 格式说明符对于您的类型不正确。
由于您的目标是 long long int
,您可以使用 strtoll
函数:
#include <stdlib.h>
long long tempNum1 = strtoll(String1, NULL, 10);
你可以这样尝试 strol:
long strtol (const char *Str, char **EndPoint, int Base)
或
long long strtoll( const char *restrict str, char **restrict str_end, int base );
atoi 说:
The call atoi(str) shall be equivalent to:
(int) strtol(str, (char **)NULL, 10)
except that the handling of errors may differ. If the value cannot be
represented, the behavior is undefined.
尝试
sscanf( String1, "%lld", &TempNum1);
请注意,格式说明符 %lld 适用于 C99,如果不是 C99,请查看编译器文档
我有一个包含 14 位数字的字符串。
我想将字符串转换为整数。
当我使用 atoi(stringName) 时,我得到了最大 32 位的限制。
示例:
String1 包含“201400000000”
long long tempNum1;
tempNum1 = atoi(String1);
printf("%d",tempNum1);
输出为:2147483647
如何将此字符串转换为数字?我想将它与其他数字串进行比较,找出最大的一个。 (我有3串14位数字,想求哪个最小,哪个最大)
atoi
returns 一个 int
.
那个int
分配给了一个long long
,但是到那时已经达到了限制。
您想使用 atoll
其中 returns 一个 long long
。
并且您的 printf 格式说明符对于您的类型不正确。
由于您的目标是 long long int
,您可以使用 strtoll
函数:
#include <stdlib.h>
long long tempNum1 = strtoll(String1, NULL, 10);
你可以这样尝试 strol:
long strtol (const char *Str, char **EndPoint, int Base)
或
long long strtoll( const char *restrict str, char **restrict str_end, int base );
atoi 说:
The call atoi(str) shall be equivalent to:
(int) strtol(str, (char **)NULL, 10)
except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.
尝试
sscanf( String1, "%lld", &TempNum1);
请注意,格式说明符 %lld 适用于 C99,如果不是 C99,请查看编译器文档