Sort out data type conversion

Source: Internet
Author: User
How to sort out annoying data type conversions

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
  • _ 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;

    //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //////////////////

  • This topic demonstrates how to convert various C ++ string types to other strings. The string types that can be converted includeChar *,Wchar_t *, _ Bstr_t, CComBSTR, CString, basic_string, and System. String. In all cases, a copy of the string is created when a string is converted to a new type. Any changes made to the new string will not affect the original string, and vice versa.

    Example of conversion from char *

    This example shows howChar *Convert to other string types listed above.

    // convert_from_char.cpp// compile with /clr /link comsuppw.lib#include <iostream>#include <stdlib.h>#include <string>#include "atlbase.h"#include "atlstr.h"#include "comutil.h"using namespace std;using namespace System;int main(){    char *orig = "Hello, World!";    cout << orig << " (char *)" << endl;    // Convert to a wchar_t*    size_t origsize = strlen(orig) + 1;    const size_t newsize = 100;    size_t convertedChars = 0;    wchar_t wcstring[newsize];    mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);    wcscat_s(wcstring, L" (wchar_t *)");    wcout << wcstring << endl;    // Convert to a _bstr_t    _bstr_t bstrt(orig);    bstrt += " (_bstr_t)";    cout << bstrt << endl;    // Convert to a CComBSTR    CComBSTR ccombstr(orig);    if (ccombstr.Append(L" (CComBSTR)") == S_OK)    {        CW2A printstr(ccombstr);        cout << printstr << endl;    }    // Convert to a CString    CString cstring(orig);    cstring += " (CString)";    cout << cstring << endl;    // Convert to a basic_string    string basicstring(orig);    basicstring += " (basic_string)";    cout << basicstring << endl;    // Convert to a System::String    String ^systemstring = gcnew String(orig);    systemstring += " (System::String)";    Console::WriteLine("{0}", systemstring);    delete systemstring;}
    Output
    Hello, World! (char *)Hello, World! (wchar_t *)Hello, World! (_bstr_t)Hello, World! (CComBSTR)Hello, World! (CString)Hello, World! (basic_string)Hello, World! (System::String)
    Example of conversion from wchar_t *

    This example shows howWchar_t *Convert to other string types listed above.

    // convert_from_wchar_t.cpp// compile with /clr /link comsuppw.lib#include <iostream>#include <stdlib.h>#include <string>#include "atlbase.h"#include "atlstr.h"#include "comutil.h"using namespace std;using namespace System;int main(){    wchar_t *orig = L"Hello, World!";    wcout << orig << L" (wchar_t *)" << endl;    // Convert to a char*    size_t origsize = wcslen(orig) + 1;    const size_t newsize = 100;    size_t convertedChars = 0;    char nstring[newsize];    wcstombs_s(&convertedChars, nstring, origsize, orig, _TRUNCATE);    strcat_s(nstring, " (char *)");    cout << nstring << endl;    // Convert to a _bstr_t    _bstr_t bstrt(orig);    bstrt += " (_bstr_t)";    cout << bstrt << endl;    // Convert to a CComBSTR    CComBSTR ccombstr(orig);    if (ccombstr.Append(L" (CComBSTR)") == S_OK)    {        CW2A printstr(ccombstr);        cout << printstr << endl;    }    // Convert to a CString    CString cstring(orig);    cstring += " (CString)";    cout << cstring << endl;    // Convert to a basic_string    wstring basicstring(orig);    basicstring += L" (basic_string)";    wcout << basicstring << endl;    // Convert to a System::String    String ^systemstring = gcnew String(orig);    systemstring += " (System::String)";    Console::WriteLine("{0}", systemstring);    delete systemstring;}
    Output
    Hello, World! (wchar_t *)Hello, World! (char *)Hello, World! (_bstr_t)Hello, World! (CComBSTR)Hello, World! (CString)Hello, World! (basic_string)Hello, World! (System::String)
    Example of conversion from _ bstr_t

    This example shows how_ Bstr_tConvert to other string types listed above.

    // convert_from_bstr_t.cpp// compile with /clr /link comsuppw.lib#include <iostream>#include <stdlib.h>#include <string>#include "atlbase.h"#include "atlstr.h"#include "comutil.h"using namespace std;using namespace System;int main(){    _bstr_t orig("Hello, World!");    wcout << orig << " (_bstr_t)" << endl;    // Convert to a char*    const size_t newsize = 100;    char nstring[newsize];    strcpy_s(nstring, (char *)orig);    strcat_s(nstring, " (char *)");    cout << nstring << endl;    // Convert to a wchar_t*    wchar_t wcstring[newsize];    wcscpy_s(wcstring, (wchar_t *)orig);    wcscat_s(wcstring, L" (wchar_t *)");    wcout << wcstring << endl;    // Convert to a CComBSTR    CComBSTR ccombstr((char *)orig);    if (ccombstr.Append(L" (CComBSTR)") == S_OK)    {        CW2A printstr(ccombstr);        cout << printstr << endl;    }    // Convert to a CString    CString cstring((char *)orig);    cstring += " (CString)";    cout << cstring << endl;    // Convert to a basic_string    string basicstring((char *)orig);    basicstring += " (basic_string)";    cout << basicstring << endl;    // Convert to a System::String    String ^systemstring = gcnew String((char *)orig);    systemstring += " (System::String)";    Console::WriteLine("{0}", systemstring);    delete systemstring;}
    Output
    Hello, World! (_bstr_t)Hello, World! (char *)Hello, World! (wchar_t *)Hello, World! (CComBSTR)Hello, World! (CString)Hello, World! (basic_string)Hello, World! (System::String)
    Example of CComBSTR Conversion

    This example shows howCComBSTRConvert to other string types listed above.

    // convert_from_ccombstr.cpp// compile with /clr /link comsuppw.lib#include <iostream>#include <stdlib.h>#include <string>#include "atlbase.h"#include "atlstr.h"#include "comutil.h"#include "vcclr.h"using namespace std;using namespace System;using namespace System::Runtime::InteropServices;int main(){    CComBSTR orig("Hello, World!");    CW2A printstr(orig);    cout << printstr << " (CComBSTR)" << endl;    // Convert to a char*    const size_t newsize = 100;    char nstring[newsize];    CW2A tmpstr1(orig);    strcpy_s(nstring, tmpstr1);    strcat_s(nstring, " (char *)");    cout << nstring << endl;    // Convert to a wchar_t*    wchar_t wcstring[newsize];    wcscpy_s(wcstring, orig);    wcscat_s(wcstring, L" (wchar_t *)");    wcout << wcstring << endl;    // Convert to a _bstr_t    _bstr_t bstrt(orig);    bstrt += " (_bstr_t)";    cout << bstrt << endl;    // Convert to a CString    CString cstring(orig);    cstring += " (CString)";    cout << cstring << endl;    // Convert to a basic_string    wstring basicstring(orig);    basicstring += L" (basic_string)";    wcout << basicstring << endl;    // Convert to a System::String    String ^systemstring = gcnew String(orig);    systemstring += " (System::String)";    Console::WriteLine("{0}", systemstring);    delete systemstring;}
    Output
    Hello, World! (CComBSTR)Hello, World! (char *)Hello, World! (wchar_t *)Hello, World! (_bstr_t)Hello, World! (CString)Hello, World! (basic_string)Hello, World! (System::String)
    Example of CString Conversion

    This example shows howCStringConvert to other string types listed above.

    // convert_from_cstring.cpp// compile with /clr /link comsuppw.lib#include <iostream>#include <stdlib.h>#include <string>#include "atlbase.h"#include "atlstr.h"#include "comutil.h"using namespace std;using namespace System;int main(){    CString orig("Hello, World!");    wcout << orig << " (CString)" << endl;    // Convert to a char*    const size_t newsize = 100;    char nstring[newsize];    strcpy_s(nstring, orig);    strcat_s(nstring, " (char *)");    cout << nstring << endl;    // Convert to a wchar_t*    // You must first convert to a char * for this to work.    size_t origsize = strlen(orig) + 1;    size_t convertedChars = 0;    wchar_t wcstring[newsize];    mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);    wcscat_s(wcstring, L" (wchar_t *)");    wcout << wcstring << endl;    // Convert to a _bstr_t    _bstr_t bstrt(orig);    bstrt += " (_bstr_t)";    cout << bstrt << endl;    // Convert to a CComBSTR    CComBSTR ccombstr(orig);    if (ccombstr.Append(L" (CComBSTR)") == S_OK)    {        CW2A printstr(ccombstr);        cout << printstr << endl;    }    // Convert to a basic_string    string basicstring(orig);    basicstring += " (basic_string)";    cout << basicstring << endl;    // Convert to a System::String    String ^systemstring = gcnew String(orig);    systemstring += " (System::String)";    Console::WriteLine("{0}", systemstring);    delete systemstring;}
    Output
    Hello, World! (CString)Hello, World! (char *)Hello, World! (wchar_t *)Hello, World! (_bstr_t)Hello, World! (CComBSTR)Hello, World! (basic_string)Hello, World! (System::String)
    Example of conversion from basic_string

    This example shows howBasic_stringConvert to other string types listed above.

    // convert_from_basic_string.cpp// compile with /clr /link comsuppw.lib#include <iostream>#include <stdlib.h>#include <string>#include "atlbase.h"#include "atlstr.h"#include "comutil.h"using namespace std;using namespace System;int main(){    string orig("Hello, World!");    cout << orig << " (basic_string)" << endl;    // Convert to a char*    const size_t newsize = 100;    char nstring[newsize];    strcpy_s(nstring, orig.c_str());    strcat_s(nstring, " (char *)");    cout << nstring << endl;    // Convert to a wchar_t*    // You must first convert to a char * for this to work.    size_t origsize = strlen(orig.c_str()) + 1;    size_t convertedChars = 0;    wchar_t wcstring[newsize];    mbstowcs_s(&convertedChars, wcstring, origsize, orig.c_str(), _TRUNCATE);    wcscat_s(wcstring, L" (wchar_t *)");    wcout << wcstring << endl;    // Convert to a _bstr_t    _bstr_t bstrt(orig.c_str());    bstrt += " (_bstr_t)";    cout << bstrt << endl;    // Convert to a CComBSTR    CComBSTR ccombstr(orig.c_str());    if (ccombstr.Append(L" (CComBSTR)") == S_OK)    {        CW2A printstr(ccombstr);        cout << printstr << endl;    }    // Convert to a CString    CString cstring(orig.c_str());    cstring += " (CString)";    cout << cstring << endl;    // Convert to a System::String    String ^systemstring = gcnew String(orig.c_str());    systemstring += " (System::String)";    Console::WriteLine("{0}", systemstring);    delete systemstring;}
    Output
    Hello, World! (basic_string)Hello, World! (char *)Hello, World! (wchar_t *)Hello, World! (_bstr_t)Hello, World! (CComBSTR)Hello, World! (CString)Hello, World! (System::String)
    Example of conversion from System: String

    This example shows howSystem. StringConvert to other string types listed above.

    // convert_from_system_string.cpp// compile with /clr /link comsuppw.lib#include <iostream>#include <stdlib.h>#include <string>#include "atlbase.h"#include "atlstr.h"#include "comutil.h"#include "vcclr.h"using namespace std;using namespace System;using namespace System::Runtime::InteropServices;int main(){    String ^orig = gcnew String("Hello, World!");    Console::WriteLine("{0} (System::String)", orig);    pin_ptr<const wchar_t> wch = PtrToStringChars(orig);    // Convert to a char*    size_t origsize = wcslen(wch) + 1;    const size_t newsize = 100;    size_t convertedChars = 0;    char nstring[newsize];    wcstombs_s(&convertedChars, nstring, origsize, wch, _TRUNCATE);    strcat_s(nstring, " (char *)");    cout << nstring << endl;    // Convert to a wchar_t*    wchar_t wcstring[newsize];    wcscpy_s(wcstring, wch);    wcscat_s(wcstring, L" (wchar_t *)");    wcout << wcstring << endl;    // Convert to a _bstr_t    _bstr_t bstrt(wch);    bstrt += " (_bstr_t)";    cout << bstrt << endl;    // Convert to a CComBSTR    CComBSTR ccombstr(wch);    if (ccombstr.Append(L" (CComBSTR)") == S_OK)    {        CW2A printstr(ccombstr);        cout << printstr << endl;    }    // Convert to a CString    CString cstring(wch);    cstring += " (CString)";    cout << cstring << endl;    // Convert to a basic_string    wstring basicstring(wch);    basicstring += L" (basic_string)";    wcout << basicstring << endl;    delete orig;}
    Output
    Hello, World! (System::String)Hello, World! (char *)Hello, World! (wchar_t *)Hello, World! (_bstr_t)Hello, World! (CComBSTR)Hello, World! (CString)Hello, World! (basic_string)

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.