天天看點

CString.Format()轉換結果錯誤總結

用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函數與格式輸入與輸出

總結:前面的格式字元一定要跟後面資料類型對應,他不會給你自動轉換為你想要的類型

繼續閱讀