1. 字符串转换为数字
1.1. 简单转换
double atof(const char *string);
double _wtof(const wchar_t *string);
int atoi(const char *string);
__int64 _atoi64(const char *string);
int _wtoi(const wchar_t *string);
__int64 _wtoi64(const wchar_t *string);
long atol(const char *string);
long _wtol(const wchar_t *string);
1.2. 指定转换基数
double strtod(const char *nptr, char **endptr);
double wcstod(const wchar_t *nptr, wchar_t **endptr );
unsigned __int64 _strtoui64(const char *nptr, char **endptr, int base);
unsigned __int64 _wcstoui64( const wchar_t *nptr, wchar_t **endptr, int base );
long strtol(const char *nptr, char **endptr, int base );
long wcstol(const wchar_t *nptr, wchar_t **endptr, int base);
string = "0xa10110This stopped it";
string = "a10110This stopped it"; // 均可
long lVal = strtol(string, &stopstring, 16);
1.3. 字符串格式化转换
char szFloat[]="123.321";
float fVal = 0.0;
sscanf_s(szFloat, "%f", &fVal);
char szDouble[] = "3.1415926535897";
double dVal = 0.0;
sscanf_s(szDouble, "%lf", &dVal);
2. 数字转字符串
2.1. sprintf_s
char szVal[32] = {0};
unsigned _int64 val = 121222222222;
sprintf_s(szVal, sizeof(szTemp), "%llx", val);
2.2. CString.Format
CString strVal;
UINT uVal = 0x12345;
strVal.Format("%#.8x", uVal); // 0x00012345
3. 附字符串格式化表
类型 | 意义 |
---|---|
%d | 十进制有符号整型 |
%u | 十进制无符号整型 |
%f | 单精度浮点类型 |
%lf | 双精度浮点类型 |
%x | 16整形 |
%s | 字符串类型 |
%c | 单个字符 |
%p | 指针的值 |
%lld | 64位十进制有符号整形 |
%llu | 64位十进制无符号整形 |
%llx | 64位十六进制整形 |
4. 格式化字符串形式
[标志][输出最小宽度][.精度][长度]类型
4.1. 标志
-
- 输出符号(正号或负号)空格输出值为正时冠以空格,为负时冠以负号
-
- 结果左对齐,右边填空格
- # 对o类, 在输出时加前缀。对x类,在输出时加前缀0x。
4.2. 输出最小宽度
用十进制整数来表示输出的最少位数。 若实际位数多于定义的宽度,则按实际位数输出, 若实际位数少于定义的宽度则补以空格或0。
4.3. 精度
精度格式符以“.”开头,后跟十进制整数。本项的意义是:如果输出数字,则表示小数的位数;如果输出的是字符, 则表示输出字符的个数;若实际位数大于所定义的精度数,则截去超过的部分。
4.4. 长度
例如: %6.9s 表示显示一个长度不小于6且不大于9的字符串。若大于9, 则第9个字符以后的内容将被删除。
5. 字符串处理
5.1. %[ ] 用法
%[ ]表示要读入一个字符集合, 如果[ 后面第一个字符是”^”,则表示反意思。遇不到第一个不满足要求的即停止截取字符串。*表示跳过当前的获取。
char szVal[32] = {0};
char szSrc[]="HELLOkitty12349ABC";
sscanf_s(szSrc, "%[A-Z]", szVal, sizeof(szVal)); // szValue = HELLO,遇到小写的k停止。
sscanf_s(szSrc, "%[A-Z,a-z]", szVal, sizeof(szVal)); // szValue = HELLOkitty,遇到数字1停止
sscanf_s(szSrc, "%[HEk]", szVal, sizeof(szVal)); // szValue = HE,遇到L不满足集合要求停止。
sscanf_s(szSrc, "%[^a-z]", szVal, sizeof(szVal)); // szValue = HELLO,遇到k属于小写停止
sscanf_s(szSrc, "%[^1234]", szVal, sizeof(szVal)); // szValue = HELLOkitty,遇到数字1停止
sscanf_s(szSrc, "%*[A-Z]%s", szVal, sizeof(szVal)); // szValue = kitty12349ABC,跳过大写字母
sscanf_s(szSrc, "%*[A-Z]%[a-z]", szVal, sizeof(szVal));// szValue = kitty,跳过大写,只获取小写
// szValue = 12349,跳过所有字母,只要数字
sscanf_s(szSrc, "%*[A-Z]%*[a-z]%[1-9]", szVal, sizeof(szVal));
// szValue = ABC,跳过前面大写,小写,数字,然后获取后面所有字符
sscanf_s(szSrc, "%*[A-Z]%*[a-z]%*[1-9]%s", szVal, sizeof(szVal));