How to convert program parameter from argv
to int64_t
? atoi()
is suitable only for 32 bit integers.
To convert string to int in Golang, use the strconv. ParseInt() method.
To convert a Double value to an Int64 value, use the Convert. ToInt64() method. Int64 represents a 64-bit signed integer.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
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; }
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With