今天写程序在用到CString对象的函数Format的时候,出现了错误:error C2664: "void ATL::CStringT<BaseType,StringTraits>::Format(const wchar_t*,...)。在网上搜了一下,找到一个比较好的答案。
问题:
CString strDate,strTime;
SYSTEMTIME st; //获取本地时间
GetLocalTime(&st);
strDate.Format("%4d-%2d-%2d",st.wYear,st.wMonth,st.wDay);
strTime.Format("【%4d:%2d:%2d】",st.wHour,st.wMinute,st.wSecond);
GetDlgItem(IDC_STATIC_Time)->SetWindowText(strDate + strTime);
SetTimer(1,1000,NULL);
return TRUE;
error C2664: “void ATL::CStringT<BaseType,StringTraits>::Format(const wchar_t *,...)”: 不能将参数 1 从“const char [12]”转换为“const wchar_t *”
回答:
VC2005及更高版本默认使用Unicode字符集,CString里存的是宽字符,也就是wchar_t,而不再是char。你可以这么写: strDate.Format(_T("%4d-%2d-%2d"),st.wYear,st.wMonth,st.wDay); strTime.Format(_T("%4d:%2d:%2d"),st.wHour,st.wMinute,st.wSecond); 以后写程序的时候,定义字符串变量,不要用char*,而用TCHAR*。所有字符串常量,不要直接用"",而要用_T("")。举个例子: TCHAR* str = _T( "Hello, World" ); MessageBox( _T( "Hello" )); 当然,我上面说的是在MFC里面。写控制台程序的话,就不用了。