字符串转换成数字
首先,不建议使用sscanf和atoi、atol、atoll、atof,它们无法检测溢出,而且atoX系列无法得知转换在何时结束。
C89函数,字节字符串:
C95函数,宽字符串:
C99函数,字节字符串(需要VC2013):
C99函数,宽字符串(需要VC2013):
MSVC函数,字节字符串:
MSVC函数,宽字符串:
// long long and unsigned long long
#define strtoll _strtoi64
#define strtoull _strtoui64
#define wcstoll _wcstoi64
#define wcstoull _wcstoui64
// intmax_t and uintmax_t
#define strtoimax _strtoi64
#define strtoumax _strtoui64
#define wcstoimax _wcstoi64
#define wcstoumax _wcstoui64
// float
static float strtof(char *pstr, char **ppend) {
double dblval = strtod(pstr, ppend);
if ((_finite(dblval) && !_finite((float)dblval)) ||
(dblval != 0 && (float)dblval == 0)) {
errno = ERANGE;
}
return (float)dblval;
}
static float wcstof(wchar_t *pstr, wchar_t **ppend) {
double dblval = wcstod(pstr, ppend);
if ((_finite(dblval) && !_finite((float)dblval)) ||
(dblval != 0 && (float)dblval == 0)) {
errno = ERANGE;
}
return (float)dblval;
}
// long double
static long double strtold(char *pstr, char **ppend) { double dblval = strtod(pstr, ppend); return dblval; }
static long double wcstold(wchar_t *pstr, wchar_t **ppend) { double dblval = wcstod(pstr, ppend); return dblval; }
数字转换成字符串
数字转换成字符串,一般使用sprintf系列。由于一些历史的原因,sprintf系列函数发生了比较复杂的演化。
不安全版本函数的支持情况:
安全版本函数的支持情况:
如果不需要安全性,可以直接使用sprintf和_swprintf。
如果需要兼容老版本VC,需要使用_snprintf和_snwprintf。
如果只需要兼容VC2005+,可以使用_snprintf和swprintf。
如果只需要兼容VC2015+,可以使用snprintf和swprintf。
注意_snprintf和_snwprintf和标准的版本不同:
_snprintf和_snwprintf字符串不溢出时会用一个0截断,字符串溢出时不会截断。
VC2015:
char buf[bufsz];
snprintf(buf, bufsz, "fmt", ...);
老版本VC实现方法:
char buf[bufsz];
memset(buf, 0, bufsz);
_snprintf(buf, bufsz - 1, "fmt", ...);
如果需要动态分配内存:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *buf = NULL;
int reqsz = 0;
reqsz = _snprintf(NULL, 0, "%d", 12);
buf = malloc(reqsz + 1);
memset(buf, 0, reqsz + 1);
_snprintf(buf, reqsz, "%d", 12);
printf("%s\n", buf);
free(buf);
return 0;
}
</stdlib.h></string.h></stdio.h>