How to convert string to int64_t?

pmichna picture pmichna · Jun 8, 2013 · Viewed 40.7k times · Source

How to convert program parameter from argv to int64_t? atoi() is suitable only for 32 bit integers.

Answer

chux - Reinstate Monica picture chux - Reinstate Monica · Jun 8, 2013

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;
}