32

I can convert a Double to a CString using _ecvt

result_str=_ecvt(int,15,&decimal,&sign);

So, is there a method like the one above that converts an int to CString?

miguel
  • 73
  • 1
  • 2
  • 7
Eslam Hamdy
  • 7,126
  • 27
  • 105
  • 165

4 Answers4

77

Here's one way:

CString str;
str.Format("%d", 5);

In your case, try _T("%d") or L"%d" rather than "%d"

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
  • 1
    Can't do it much faster than that. You may want to wrap the string with the `_T` macro to match the `LPCTSTR` parameter type. – user1201210 Sep 26 '12 at 13:15
  • 2
    @Eslam How specifically did it not work? Didn't compile? Runtime error? Wrong result? – user1201210 Sep 26 '12 at 13:17
  • @Daniel, the following error arises error C2664: 'void ATL::CStringT::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [3]' to 'const wchar_t *' – Eslam Hamdy Sep 26 '12 at 13:18
  • 7
    @Eslam Try `_T("%d")` or `L"%d"` rather than `"%d"`. – user1201210 Sep 26 '12 at 13:19
  • It is not working for me! I am getting error 'cannot convert argument 1 from 'const char [3]' to 'const unsigned short *'. Weird. – ZoomIn Mar 18 '22 at 10:45
8

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

snowdude
  • 3,854
  • 1
  • 18
  • 27
0
template <typename Type>
CString ToCString (Type value)
    {
    return std::to_wstring (value).data ();
    }

int main ()
    {
    const auto msg = ToCString (10);
    std::wcout << msg.GetString () << std::endl;

    return 0;
    }
Catriel
  • 461
  • 3
  • 11
0
CString(std::to_string(123).c_str())
Jesse Hufstetler
  • 583
  • 7
  • 13