How can I convert an Int to a CString?
Asked Answered
M

4

33

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?

Mycah answered 26/9, 2012 at 13:10 Comment(2)
Note: The cstring tag is for the standard C++ header cstring, not for Microsofts string thing.Galling
Maybe itoa is what you are looking for?Baker
Z
79

Here's one way:

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

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

Zellner answered 26/9, 2012 at 13:13 Comment(5)
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.Highstepper
@Eslam How specifically did it not work? Didn't compile? Runtime error? Wrong result?Highstepper
@Daniel, the following error arises error C2664: 'void ATL::CStringT<BaseType,StringTraits>::Format(const wchar_t *,...)' : cannot convert parameter 1 from 'const char [3]' to 'const wchar_t *'Mycah
@Eslam Try _T("%d") or L"%d" rather than "%d".Highstepper
It is not working for me! I am getting error 'cannot convert argument 1 from 'const char [3]' to 'const unsigned short *'. Weird.Luther
R
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.

Routine answered 26/9, 2012 at 13:32 Comment(0)
C
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;
    }
Commeasure answered 25/8, 2021 at 20:5 Comment(0)
B
0
CString(std::to_string(123).c_str())
Belak answered 6/4, 2023 at 15:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.