如何将字符串转换为int64_t?

pmi*_*hna 18 c unix int64

如何将程序参数转换argvint64_tatoi()仅适用于32位整数.

chu*_*ica 12

符合C99标准的尝试.

[编辑]雇用@R.更正

// 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 聪明的想法使用`sscanf`的+1,但你需要的是`SCNd64`,而不是'PRId64`.我也不清楚`sscanf`在溢出时是否表现良好. (2认同)
  • @chux 你确定吗?根据 [this](http://pubs.opengroup.org/onlinepubs/009604599/basedefs/inttypes.h.html) `SCNd64` 用于 `scanf`,`PRId64` 用于 `printf`。 (2认同)

Ahm*_*sud 10

有几种方法可以做到:

  strtoll(str, NULL, 10);
Run Code Online (Sandbox Code Playgroud)

这符合POSIX C99标准.

你也可以用strtoimax; 它有以下原型:

 strtoimax(const char *str, char **endptr, int base);
Run Code Online (Sandbox Code Playgroud)

这很好,因为它总是可以使用本地intmax_t ...这是C99,你需要包括 <inttypes.h>


dav*_*nte 5

来自网络搜索的用户也应该考虑std::stoll

它并不能有效地严格回答这个原始问题,const char*但无论如何,许多用户都会有一个std::string。如果您不关心效率,您应该获得隐式转换(基于使用单参数构造函数的用户定义转换std::string),std::string即使您有一个const char*.

它比std::strtoll总是需要 3 个参数的更简单。

如果输入不是数字,它应该抛出,但请参阅这些注释