用Format转换字符串出现“000”和一堆神秘的数字/乱码
【1】第一个错误代码:
double ep[6]={2020,1,1,1,1,1.1};//年月日时分秒
CString str;
str.Format(_T("%.4d%.2d%.2d"), ep[0], ep[1], ep[2]);
得到的str并不是“20200101”,最后发现需要自己去将double类型的数据转换为int类型,才能使用“d”
double ep[6]={2020,1,1,1,1,1.1};//年月日时分秒
CString str;
str.Format(_T("%.4d%.2d%.2d"), (int)(ep[0]), (int)(ep[1]), (int)(ep[2]));
以上的代码就可以得到正确的结果,str=“20200101”
【2】第二个错误代码:
time_t time=154826820;//typedef __time64_t time_t; typedef __int64 __time64_t;
double fl=1.3
CString str;
str.Format(_T("%d%2.1f%"), time, f1);
//str.Format(_T("%ld %2.1f%"), time, f1);
上面的代码得到的str并不是“154826820 1.3”,而是一堆乱数字
time_t time=154826820;//typedef __time64_t time_t; typedef __int64 __time64_t;
int time2=time;
double fl=1.3
CString str;
str.Format(_T("%d%2.1f%"), time2, f1);
上面的代码就可以得到正确的结果
【3】第三个错误代码
将char[]类型的变量转换为CString时乱码
错误代码如下:
char name[8]="beijing";
CString strname;
strname.Format(_T("%s"), strname);
//strname.Format(_T("%s"), LPCWSTR(strname));
上面的strname得到的结果为乱码,需改成下面的代码:
char name[8]="beijing";
CString strname;
strname.Format(_T("%s"), (CString)strname);
有正负号的浮点数实现小数点对齐等操作请参考:CString中Format函数与格式输入与输出
总结:前面的格式字符一定要跟后面数据类型对应,他不会给你自动转换为你想要的类型