Conversion: C/C ++ data type conversion 1

Source: Internet
Author: User
(Float, Char, String, cstring)
  • Copyright Disclaimer: During reprinting, please use hyperlinks to indicate the original source and author information of the article and this statement
    Http://mrcatart.blogbus.com/logs/68590681.html

    C/C ++ data type conversion 1 (float, Char, String, cstring)

    Unicode (unified code, universal code, Single Code) is a character encoding used on a computer. It sets a unified and unique binary code for each character in each language to meet the requirements of cross-language and cross-platform text conversion and processing. R & D started in December 1990 and officially announced in December 1994. With the enhancement of computer capabilities, Unicode has been popularized in more than a decade since its launch. In a non-Unicode environment, because different countries and regions use different character sets, it is likely that all characters cannot be properly displayed. Microsoft uses the code page conversion technology to solve this problem, that is, the non-UNICODE character encoding is converted to the Unicode encoding used in the system corresponding to the same character through the specified conversion table.

    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; wchar_t
    Wchar_t is a data type of C ++ characters. Char is an 8-character type and can contain a maximum of 256 characters. Many foreign character sets contain more than 256 characters, which cannot be expressed in character type. The wchar_t data type is 16 bits, and the number of characters represents far greater than that of char.
    The wprintf () function in the Standard C ++ and classes and objects in the iostream class library can provide operations related to the wchar_t wide character type. For example:
    # Include <iostream>
    Using namespace STD;
    Void main ()
    {
    Locale LOC ("CHS"); // defines the "region Settings" as the Chinese method.
    Wcout. imbue (LOC); // Method for loading Chinese Characters
    Wchar_t STR [] = l "China"; // defines the wide character array. Note that l is in uppercase.
    Wcout <STR <Endl; // display the wide character array, the same below
    Wprintf (STR );
    System ("pause ");
    }

    I,Convert other data types to string
    1) 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
    2) long integer (long)
    Ltoa (L, temp, 10 );
    3) 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.
    4) cstring variable
    STR = "2008 Beijing Olympics ";
    Buf = (lpstr) (lpctstr) STR;
    5) BSTR variable
    BSTR bstrvalue =: sysallocstring (L "programmer ");
    Char * Buf = _ com_util: convertbstrtostring (bstrvalue );
    Sysfreestring (bstrvalue );
    Afxmessagebox (BUF );
    Delete (BUF );
    6) ccombstr variable
    Ccombstr bstrvar ("test ");
    Char * Buf = _ com_util: convertbstrtostring (bstrvar. m_str );
    Afxmessagebox (BUF );
    Delete (BUF );
    7) _ 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)
    UseSprintfComplete 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,String to other data types
    Temp = "123456 ";
    1) Short INTEGER (INT)
    I = atoi (temp );
    2) long integer (long)
    L = atol (temp );
    3) floating point (double)
    D = atof (temp );
    String s; D = atof (S. c_str ());
    4) BSTR variable
    BSTR bstrvalue =: sysallocstring (L "programmer ");
    ... // Complete the use of bstrvalue
    Sysfreestring (bstrvalue );
    5) ccombstr variable
    Ccombstr variables can be directly assigned values.
    Ccombstr bstrvar1 ("test ");
    Ccombstr bstrvar2 (temp );
    6) _ bstr_t variable
    _ Bstr_t type variables can be directly assigned values
    _ Bstr_t bstrvar1 ("test ");
    _ Bstr_t bstrvar2 (temp );

    7)String to char *

    String is one of the C ++ standard libraries, which encapsulates string operations.
    There are three methods to convert string to char:
    1. Data
    For example:
    String STR = "ABC ";
    Char * P = Str. Data ();
    2. c_str
    For example, string STR = "gdfd ";
    Char * P = Str. c_str ();
    3 copy
    For example
    String STR = "hello ";
    Char P [40];
    Str. Copy (p, 5, 0); // here, 5 represents the number of characters to be copied, and 0 represents the copy position.
    * (P + 5) = '/0'; // You must manually add the Terminator.
    Cout <P;

    III,1. 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); doubledb = 777.999; Str. Format ("%. 8f", DB); Retain 8 decimal places
    String pointer (char *) can be directly assigned 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.
    Note: Convert MFC smart device string to cstring
    String S = "123456"; cstring CSTR; CSTR = S. c_str ();

    2.Cstring to double or float

    (1) dB = atof (lpctstr) Str );

    (2) Implementation through user-defined functions

    Void cstringtofloat (cstring CSTR, double & F) // void cstringtofloat (cstring CSTR, float & F)
    {
    Int nlength = CSTR. getlength ();
    Int nbytes = widechartomultibyte (cp_acp, 0, CSTR, nlength, null, 0, null, null );
    Char * pcontentbuff = new char [nbytes + 1];
    Memset (pcontentbuff, 0, nbytes + 1 );
    Widechartomultibyte (cp_oemcp, 0, CSTR, nlength, pcontentbuff, nbytes, null, null );
    Pcontentbuff [nbytes] = 0;
    F = atof (pcontentbuff );
    }

    3.Cstring to int

    How to convert a cstring to an int is described on the Internet by using the atoi function, but the cstring is internally stored as a wchar_t character, each character occupies two bytes, And the atoi parameter is char *, each character occupies one byte. If it is forcibly converted to char *, it is converted to a string with only the first character because the high byte is null. This is wrong. the _ wtoi function should be used. The parameter of this function is wchar_t *, for example:
    Cstring STR ("123 ");
    Int num = _ wtoi (STR );
    Similarly, functions such as _ wtof () and _ wtol () can be used to convert cstring into different numerical types.

    4.Platform vc2005 uses the Unicode Character Set. Cstring type conversion to char * or char []
    The previous cstring conversion method or other online instructions are invalid.
    (1. strcpy_s (pchar, sizeof (pchar), mcstring. getbuffer (mcstring. getlength (); no, mcstring. getbuffer () returns the wchar_t array. When UNICODE character sets are used, wchar_t cannot be automatically converted to char *.
    (2. strcpy_s (pchar, sizeof (pchar), (lpcstr) _ bstr_t (mcstring); no, "_ bstr_t cannot find the identifier"
    (3. char * PCH = (T2A) (lpstr) (lpctstr) mcstring; no, "T2A is an undeclared identifier". I add the corresponding header file atlconv. h or atlbase. h.
    (4. char * PCH = (lpstr) (lpctstr) mcstring; no error is returned, but PCH can only obtain the first character of cstring, and replace the first character with (char *), only the first character can be obtained.
    (5. cstring. getbuffer (cstring. getlength () does not work. W_char * cannot be converted to _ char *.

    Use the following function
    Wstring multchartowidechar (string Str)
    {
    // Obtain the buffer size and apply for space. The buffer size is calculated by characters.
    Int Len = multibytetowidechar (cp_acp, 0, str. c_str (), str. Size (), null, 0 );
    Tchar * buffer = new tchar [Len + 1];
    // Convert multi-byte encoding to wide-byte encoding
    Multibytetowidechar (cp_acp, 0, str. c_str (), str. Size (), buffer, Len );
    Buffer [Len] = '/0'; // Add the end of the string
    // Delete the buffer and return the value
    Wstring return_value;
    Return_value.append (buffer );
    Delete [] buffer;
    Return return_value;
    }
    String widechartomultichar (wstring Str)
    {
    String return_value;
    // Obtain the buffer size and apply for space. The buffer size is calculated in bytes.
    Int Len = widechartomultibyte (cp_acp, 0, str. c_str (), str. Size (), null, 0, null, null );
    Char * buffer = new char [Len + 1];
    Widechartomultibyte (cp_acp, 0, str. c_str (), str. Size (), buffer, Len, null, null );
    Buffer [Len] = '/0 ';
    // Delete the buffer and return the value
    Return_value.append (buffer );
    Delete [] buffer;
    Return return_value;
    }
    Therefore
    String mstring = widechartomultichar (lpctstr) mcstring );
    Strcpy_s (Pach, sizeof (Pach), mstring. c_str ());
    Conversion successful!

     

    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, char * P = _ com_util: convertbstrtostring (B); Delete P;

    Ccombstr and _ bstr_t overload a large number of operators. You can directly perform = ,! =, = And so on, so it is very convenient to use.

    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.
    NT 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;

     

    The sstream> library defines three types: istringstream, ostringstream, and stringstream for stream input, output, and input/output Operations respectively. In addition, each class has a corresponding wide character set version. For simplicity, I focus on stringstream, because each conversion involves input and output operations. Example 1 shows how to use a stringstream object

    String to int type conversion

    Note: <sstream> uses a String object instead of a character array. This avoids the risk of buffer overflow. In addition, the input parameters and the type of the target object are automatically derived, even if incorrect formatting characters are used, there is no danger.

    Example 1:

    STD: stringstream stream;

    String result = "10000 ";
    Int n = 0;
    Stream <result;
    Stream> N; // n equals 10000

    Int to string type conversion

    String result;
    Int n = 12345;
    Stream <N;
    Result = stream. STR (); // result is equal to "12345"

    Reuse stringstream object

    If you want to use the same stringstream object in Multiple conversions, remember to use the clear () method before each conversion, the biggest benefit of using the same stringstream (instead of creating a new object each time) in Multiple conversions is efficiency. Stringstream Object Construction and destructor are usually very CPU-consuming. After testing, using clear () alone cannot clear the content of the stringstream object, but only the status of the object. to reuse the same stringstream object, you must use STR () reinitialize the object.

    Example 2:

    STD: stringstream strsql;
    For (INT I = 1; I <10; ++ I)
    {
    Strsql <"insert into test_tab values (";
    Strsql <I <"," <(I + 10) <");";
    STD: String STR = strsql. STR (); // obtain the string
    Res = sqlite3_exec (PDB, str. c_str (), 0, & errmsg );

    STD: cout <strsql. STR () <STD: Endl;

    Strsql. Clear ();
    Strsql. STR ("");
    }

Related Article

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.