How to convert string to int64_t?
A C99 conforming attempt.
[edit] employed @R. correction
// Note: Typical values of SCNd64 include "lld" and "ld".
#include <inttypes.h>
#include <stdio.h>
int64_t S64(const char *s) {
int64_t i;
char c ;
int scanned = sscanf(s, "%" SCNd64 "%c", &i, &c);
if (scanned == 1) return i;
if (scanned > 1) {
// TBD about extra data found
return i;
}
// TBD failed to scan;
return 0;
}
int main(int argc, char *argv[]) {
if (argc > 1) {
int64_t i = S64(argv[1]);
printf("%" SCNd64 "\n", i);
}
return 0;
}
Users coming from a web search should also consider std::stoll
.
It doesn't strictly answer this original question efficiently for a const char*
but many users will have a std::string
anyways. If you don't care about efficiency you should get an implicit conversion (based on the user-defined conversion using the single-argument std::string
constructor) to std::string
even if you have a const char*
.
It's simpler than std::strtoll
which will always require 3 arguments.
It should throw if the input is not a number, but see these comments.
There are a few ways to do it:
strtoll(str, NULL, 10);
This is POSIX C99 compliant.
you can also use strtoimax; which has the following prototype:
strtoimax(const char *str, char **endptr, int base);
This is nice because it will always work with the local intmax_t ... This is C99 and you need to include <inttypes.h>