How to perform type conversion in vc, such as converting an integer to a string or converting a string to an integer

Source: Internet
Author: User

Those who are new to VC programming are often confused about the conversion of many data types. This article will introduce the use of some common data types.
Let's first define some common type variables to illustrate

Int I = 100;
Long l = 2001;
Float f = 300.2;
Double d = 12345.119;
Char username [] = "Cheng peijun ";
Char temp [200];
Char * buf;
CString str;
_ Variant_t v1;
_ Bstr_t v2;

1. convert other data types to strings

  • Short INTEGER (int)

    Itoa (I, temp, 10); // convert I to a string and put it into temp. the last digit indicates decimal.
    Itoa (I, temp, 2); // convert in binary mode
  • Long (long)

    Ltoa (l, temp, 10 );
  • Floating Point Number (float, double)

    Fcvt can be used to complete the conversion. This is an example in MSDN:
    Int decimal, sign;
    Char * buffer;
    Double source = 3.1415926535;
    Buffer = _ fcvt (source, 7, & decimal, & sign );
    Running result: source: 3.1415926535 buffer: '20180101' decimal: 1 sign: 0
    Decimal indicates the decimal point position, sign indicates the symbol: 0 is a positive number, and 1 is a negative number.
  • CString variable

    Str = "2008 Beijing Olympics ";
    Buf = (LPSTR) (LPCTSTR) str;
  • BSTR variable

    BSTR bstrValue =: SysAllocString (L "programmer ");
    Char * buf = _ com_util: ConvertBSTRToString (bstrValue );
    SysFreeString (bstrValue );
    AfxMessageBox (buf );
    Delete (buf );
  • CComBSTR variable

    CComBSTR bstrVar ("test ");
    Char * buf = _ com_util: ConvertBSTRToString (bstrVar. m_str );
    AfxMessageBox (buf );
    Delete (buf );
  • _ Bstr_t variable

    _ Bstr_t is the encapsulation of BSTR. It is easy to use because = operator has been overloaded.
    _ Bstr_t bstrVar ("test ");
    Const char * buf = bstrVar; // do not modify the buf content
    AfxMessageBox (buf );
  • General method (for non-COM data types)

    Use sprintf to complete the conversion
    char  buffer[200];
    char c = '1';
    int i = 35;
    long j = 1000;
    float f = 1.7320534f;
    sprintf( buffer, "%c",c);
    sprintf( buffer, "%d",i);
    sprintf( buffer, "%d",j);
    sprintf( buffer, "%f",f);

Ii. Convert strings to other data types


Strcpy (temp, "123 ");

  • Short INTEGER (int)

    I = atoi (temp );
  • Long (long)

    L = atol (temp );
  • Floating Point (double)

    D = atof (temp );
  • CString variable

    CString name = temp;
  • BSTR variable

    BSTR bstrValue =: SysAllocString (L "programmer ");
    ... // Complete the use of bstrValue
    SysFreeString (bstrValue );
  • CComBSTR variable

    CComBSTR variables can be directly assigned values.
    Ccombstr bstrvar1 ("test ");
    Ccombstr bstrvar2 (temp );
  • _ Bstr_t variable

    _ Bstr_t type variables can be directly assigned values
    _ Bstr_t bstrvar1 ("test ");
    _ Bstr_t bstrvar2 (temp );

Iii. convert other data types to cstring


Use the cstring member function Format for conversion. For example:

  • INTEGER (INT)
    Str. Format ("% d", I );
  • Float)
    Str. Format ("% F", I );
  • Data Types supported by cstring constructors, such as string pointers (char *), can be directly assigned values.
    STR = username;
  • For data types not supported by format, you can convert the data type to char * by using the method described above, and then assign the value to the cstring variable.

Iv. BSTR, _ bstr_t and ccombstr

  • Ccombstr is the encapsulation of BSTR by ATL, _ bstr_t is the encapsulation of BSTR by C ++, and BSTR is a 32-bit pointer, but it does not directly point to the buffer of the string.
    Char * can be converted to BSTR as follows:
    Bstr B = _ com_util: convertstringtobstr ("data"); // comutil. h and comsupp. Lib must be added before use.
    Sysfreestring (bstrvalue );
    Otherwise, you can use
    Char * P = _ com_util: convertbstrtostring (B );
    Delete P;
    For details, refer to the specific descriptions in sections 1 and 2.

    CComBSTR and _ bstr_t overload a large number of operators. You can directly perform = ,! =, = And so on, so it is very convenient to use.
    Especially _ bstr_t. We recommend that you use it.

 

V. VARIANT, _ variant_t, and COleVariant

  • For the VARIANT Structure, refer to the definition of the tagVARIANT struct in the header file VC98/Include/OAIDL. H.
    Assign a value to the VARIANT variable: assign a value to the vt member to specify the data type, and then assign a value to the variable of the same data type in the union structure. For example:
    VARIANT va;
    Int a = 2001;
    Va. vt = VT_I4; // specify Integer Data
    Va. lVal = a; // value assignment

    For VARIANT that is not immediately assigned a value, it is best to initialize with Void VariantInit (variantarg far * pvarg); in essence, the vt is set to VT_EMPTY, the following table lists the correspondence between vt and common data:

    Byte bVal; // VT_UI1.
    Short iVal; // VT_I2.
    Long lVal; // Vt_i4.
    Float fltval; // Vt_r4.
    Double dblval; // Vt_r8.
    Variant_bool boolval; // Vt_bool.
    Scode; // Vt_error.
    Cy cyval; // Vt_cy.
    Date; // Vt_date.
    BSTR bstrval; // Vt_bstr.
    Decimal far * pdecval // Vt_byref | vt_decimal.
    Iunknown far * punkval; // Vt_unknown.
    Idispatch far * pdispval; // Vt_dispatch.
    Safearray far * parray; // Vt_array | *.
    Byte far * pbval; // Vt_byref | vt_ui1.
    Short far * pival; // Vt_byref | vt_i2.
    Long far * plval; // Vt_byref | vt_i4.
    Float FAR * pfltVal; // VT_BYREF | VT_R4.
    Double FAR * pdblVal; // VT_BYREF | VT_R8.
    VARIANT_BOOL FAR * pboolVal; // VT_BYREF | VT_BOOL.
    Scode far * pscode; // VT_BYREF | VT_ERROR.
    Cy far * pcyVal; // VT_BYREF | VT_CY.
    Date far * pdate; // VT_BYREF | VT_DATE.
    Bstr far * pbstrVal; // VT_BYREF | VT_BSTR.
    IUnknown FAR * ppunkVal; // VT_BYREF | VT_UNKNOWN.
    IDispatch FAR * ppdispVal; // VT_BYREF | VT_DISPATCH.
    Safearray far * pparray; // VT_ARRAY | *.
    Variant far * pvarVal; // VT_BYREF | VT_VARIANT.
    Void FAR * byref; // Generic ByRef.
    Char cVal; // VT_I1.
    Unsigned short uival; // Vt_ui2.
    Unsigned long ulval; // Vt_ui4.
    Int intval; // Vt_int.
    Unsigned int uintval; // Vt_uint.
    Char far * pcval; // Vt_byref | vt_i1.
    Unsigned short far * puival; // Vt_byref | vt_ui2.
    Unsigned long far * pulval; // Vt_byref | vt_ui4.
    Int far * pintval; // Vt_byref | vt_int.
    Unsigned int far * puintval; // Vt_byref | vt_uint.
  • _ Variant_t is the encapsulation class of variant, and its value assignment can be forced type conversion. Its constructor will automatically process these data types.
    # Include <comdef. h> must be added for use.
    For example:
    Long L = 222;
    Ing I = 100;
    _ Variant_t lval (L );
    Lval = (long) I;
  • The use of colevariant is basically the same as that of the _ variant_t method. See the following example:
    Colevariant V3 = "string", V4 = (long) 1999;
    Cstring STR = (BSTR) v3.pbstrval;
    Long I = v4.lval;

    6. Other COM Data Types

    • Obtain CLSID Based on ProgID
      HRESULT CLSIDFromProgID (LPCOLESTR lpszProgID, LPCLSID pclsid );
      CLSID clsid;
      CLSIDFromProgID (L "MAPI. Folder", & clsid );
    • Obtain the ProgID Based on CLSID.
      WINOLEAPI ProgIDFromCLSID (REFCLSID clsid, LPOLESTR * lplpszProgID );
      For example, we have defined CLSID_IApplication. The following code gets the ProgID
      LPOLESTR pProgID = 0;
      ProgIDFromCLSID (CLSID_IApplication, & pProgID );
      ... // You can use pProgID
      CoTaskMemFree (pProgID); // do not forget to release

    VII. ANSI and Unicode


    Unicode is a string of the wide character type, and all Unicode strings are used in COM.

    • Convert ANSI to Unicode
      (1) Use the macro L, for example, CLSIDFromProgID (L "MAPI. Folder", & clsid );
      (2) Implement conversion through the MultiByteToWideChar function, for example:
      Char * szProgID = "MAPI. Folder ";
      WCHAR szWideProgID [128];
      CLSID clsid;
      Long lLen = MultiByteToWideChar (CP_ACP, 0, szProgID, strlen (szProgID), szWideProgID, sizeof (szWideProgID ));
      SzWideProgID [lLen] = '/0 ';
      (3) using the A2W macro, for example:
      Uses_conversion;
      Clsidfromprogid (a2w (szprogid), & CLSID );
    • Convert Unicode to ANSI
      (1) Use widechartomultibyte, for example:
      // Assume that you already have a unicode string wszsomestring...
      Char szansistring [max_path];
      Widechartomultibyte (cp_acp, wc_compositecheck, wszsomestring,-1, szansistring, sizeof (szansistring), null, null );
      (2) Use the w2a macro, for example:
      Uses_conversion;
      Ptemp = w2a (wszsomestring );

    8. Others

    • During message processing, we often need to split wparam, lparam, and other 32-bit data (DWORD) into two 16-bit data (Word), for example:
      Lparam;
      Word lovalue = loword (lparam); // take 16 bits
      Word hivalue = hiword (lparam); // you can specify 16 characters in height.
    • For a 16-bit data (Word), we can use the same method to break down the high and low 8-bit data (byte), for example:
      Word wvalue;
      Byte lovalue = lobyte (wvalue); // get 8 bits
      Byte hivalue = hibyte (wvalue); // get the 8-bit high
    • Two 16-bit data (WORD) to synthesize 32-bit data (DWORD, LRESULT, LPARAM, or WPARAM)
      Long makelong (WORD wLow, WORD wHigh );
      Wparam makewparam (WORD wLow, WORD wHigh );
      Lparam makelparam (WORD wLow, WORD wHigh );
      Lresult makelresult (WORD wLow, WORD wHigh );
    • Two 8-bit data (BYTE) to synthesize 16-bit data (WORD)
      Word makeword (BYTE bLow, BYTE bHigh );
    • Obtain the COLORREF color value from R (red), G (green), and B (blue ).
      Colorref rgb (BYTE byRed, BYTE byGreen, BYTE byBlue );
      For example, COLORREF bkcolor = RGB (0x22,0x98,0x34 );
    • From COLORREF color value to RGB color value
      BYTE Red = GetRValue (bkcolor); // get the Red color
      BYTE Green = GetGValue (bkcolor); // obtain the Green color.
      BYTE Blue = GetBValue (bkcolor); // obtain the Blue color

    IX. Precautions


    To use ConvertBSTRToString, add the header file comutil. h, add comsupp. lib to setting, or directly add # pragma comment (lib, "comsupp. lib ")

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.