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)
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>
来自网络搜索的用户也应该考虑std::stoll。
它并不能有效地严格回答这个原始问题,const char*但无论如何,许多用户都会有一个std::string。如果您不关心效率,您应该获得隐式转换(基于使用单参数构造函数的用户定义转换std::string),std::string即使您有一个const char*.
它比std::strtoll总是需要 3 个参数的更简单。
如果输入不是数字,它应该抛出,但请参阅这些注释。
| 归档时间: |
|
| 查看次数: |
29499 次 |
| 最近记录: |