将字符串转换为long long C?

时间:2013-05-03 21:15:19

标签: c string casting

如何在C中将字符串转换为long long?

我有

char* example = "123";

我想将示例转换为很长的时间,所以我想要像

这样的东西
long long n = example;

我该怎么做?

1 个答案:

答案 0 :(得分:11)

使用函数strtoll

#include <stdlib.h>
#include <errno.h>

char const * example = "123";

char * e;
errno = 0;

long long int n = strtoll(example, &e, 0);

if (*e != 0 || errno != 0) { /* error, don't use n! */ }

实际上,e将指向转换序列之后的下一个字符,因此您可以使用此方法进行更复杂的解析。就目前而言,我们只检查整个序列是否已经转换。您还可以检查errno以查看是否发生溢出。有关详细信息,请参阅the manual

(对于历史兴趣:{C}引入了long long intstrtoll。它们在C89 / 90中不可用。等效函数strtol / strtoul / {{但是,存在。)

相关问题