IT-info > C / C++ > Diverse

C / C++

C++ / WIN32 API - Int string conversion

Data Conversion
itoa() — Convert int into a string
Easiest way to convert int to string in C++
itoa, _itoa, ltoa, _ltoa, ultoa, _ultoa, _i64toa, _ui64toa, _itow, _ltow, _ultow, _i64tow, _ui64tow  (Visual Studio 2017)
_itoa_s, _ltoa_s, _ultoa_s, _i64toa_s, _ui64toa_s, _itow_s, _ltow_s, _ultow_s, _i64tow_s, _ui64tow_s  (Visual Studio 2017)
argument of type const char* is incompatible with parameter of type “LPCWSTR”
C++ Templates Tutorial
invalid cruntime parameter _itoa_s
How to parse a string to an int in C++?
How do you convert a C++ string to an int?

template <size_t size>
errno_t _itow_s( int value, wchar_t (&buffer)[size], int radix );

Convert int to string in win32 API

Usually what you'll want is to use the wide-character alternative to _itoa(). In this case, you'd want _itow().

So you'd do it like this:

case WM_PAINT: {
    hdc = BeginPaint(hWnd, &ps);
    SYSTEMTIME lt;
    GetLocalTime(<);
    WCHAR info[20];
    _itow(lt.wHour, info, 16);
    TextOut(hdc, 200, 200, info, wcslen(info));
    EndPaint(hdc, &ps);
}
break;

Particularly, note the use of WCHAR instead of CHAR, _itow() instead of _itoa() and wcslen() instead of strlen().

Also, note the distinction of the length of the string "in characters" (as the documentation of TextOut() points out) and its length "in bytes". In a so-called "Ansi string", they are identical, but in WCHAR strings they are different (each character in the BMP takes two bytes; each character outside of the BMP takes four).

Otherwise, the code is directly analogous. In time you'll get the hang of using these wide-character string functions rather than the regular ones when programming using UTF-16.

itoa

Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary.

/* itoa example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
    int i;
    char buffer [33];
    printf ("Enter a number: ");
    scanf ("%d",&i);
    itoa (i,buffer,10);
    printf ("decimal: %s\n",buffer);
    itoa (i,buffer,16);
    printf ("hexadecimal: %s\n",buffer);
    itoa (i,buffer,2);
    printf ("binary: %s\n",buffer);
    return 0;
}

Output:
Enter a number: 1750
decimal: 1750
hexadecimal: 6d6
binary: 11011010110