开发者

Error converting types in C++

I have a program in which I need to use the Format(); function to combine a string literal and a int into a CString variable. I have tried several different ways of doing this, the code for them is here:

// declare variables used
CString _CString;
int _int;

// try to use format function with string literal
_CString.Format("text",_int); 

// try to use format function with C-Style cast
_CString.Format((wchar_t)"text",_int);

// try to use format function with static_cast 
_CString.Format(static_cast<wchar_t>("text"),_int);

The first one returns error C2664: 'void ATL::CStringT::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [33]' to 'const wchar_t *'

For the second, there is no error but the text appears in Chinese characters.

The third one ret开发者_如何学Pythonurns error C2440: 'static_cast' : cannot convert from 'const char [33]' to 'wchar_t'

Any ideas for converting CStrings to wchar_t *s?

Thanks


Well, it's not entirely clear what string type you'd like to target but here's what I'd be doing:

_CString.Format(_T("%d"), _int);

Attempting to type cast a multi-byte string to a Unicode string may compile, but it's asking for trouble because it's still a multi-byte string. You'll need to convert the entire string and not just typecast it if that's what you want.


The problem is that you're performing a UNICODE build (which is fine), so the

_CString.Format(); 

function i expecting the first parameter to be a wide character string. You need to use the L"" syntax to form a wide-character string literal:

_CString.Format(L"text",_int); 

Of course, you'll need a specifier to actually get the int variable formatted into the CString:

_CString.Format(L"text: %d",_int); 

If you include the tchar.h header, you can use Microsoft's macros to make the string literal wide-character or regular-old-character (otherwise known as ANSI) depending on whether you're building UNICODE or not:

_CString.Format(_T("text: %d)",_int); 

but I'd say that unless you're planning to support legacy stuff that'll require ANSI support, I probably wouldn't bother with the tchar.h stuff.


Try the mbstowcs function. http://msdn.microsoft.com/en-us/library/ms235631(v=vs.80).aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜