Search code examples
c++visual-studio-2010cstringwchar-tstatic-cast

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 returns error C2440: 'static_cast' : cannot convert from 'const char [33]' to 'wchar_t'

Any ideas for converting CStrings to wchar_t *s?
Thanks


Solution

  • 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.