Conversion between C + + data type and raw data data types in C + +

Source: Internet
Author: User
Tags arrays character set ole sprintf

conversion between the data type in GLM and the original data (c + + array)

float*-> GLM::VEC3

Float g_axisdirection[] = {0.0f, 1.0f, 0.0f};

GLM::MAKE_VEC3 (g_axisdirection)

glm::mat4->float*

Glm::mat4 Rx = GLM::MAT4 (1);

(float*) glm::value_ptr (Rx)


conversion of various data types in C + +

%f Common data types use conversion details

Leo

To convert CString to char* in a Unicode character set environment

Method:

CString str = _t ("d://in-school project//qq.bmp")//////leo This NB can be lowered to the Unicode CString converted to char*
declaring identifiers
Uses_conversion;
Calling functions, both T2A and W2A support character conversions in ATL and MFC
char * pfilename = T2A (str);
char * pfilename = W2A (str); Transformations can also be implemented



In Visual C + +. In NET2005, the default character set is Unicode, but in projects such as VC6.0, the default character set is the multibyte character set (Mbcs:multi-byte Character set). This results in a very simple and useful variety of character operations and functions in the VC6.0 that run in the VS2005 environment and report a variety of errors, summarized here in Visual C + +. Several ways to convert CString and char * in the Unicode character set in the NET2005 environment are, in fact, the Unicode character set and the MBCS character set conversion.

1, Unicode under CString conversion to char *

Method one: Using Api:widechartomultibyte for conversion

CString str = _t ("d://in-school project//qq.bmp");

Note: The values of the following N and Len are different, n is calculated by character, Len is measured in bytes
int n = str.     GetLength (); n =, Len = 18

Gets the size of a wide-byte character, measured in bytes
int len = WideCharToMultiByte (cp_acp,0,str,str. GetLength (), null,0,null,null);

Request space for multibyte-character arrays, size of byte bytes in bytes
char * pfilename = new char[len+1]; In units of bytes

Convert wide-byte encoding to multi-byte encoding
WideCharToMultiByte (cp_acp,0,str,str. GetLength (), pfilename,len,null,null);

PFILENAME[LEN+1] = '/0 '; Multibyte characters end With '/0 '

Method Two: Use function: T2A, W2A

CString str = _t ("d://in-school project//qq.bmp");

declaring identifiers
Uses_conversion;

Calling functions, both T2A and W2A support character conversions in ATL and MFC
char * pfilename = T2A (str);
char * pfilename = W2A (str); Transformations can also be implemented

Note: Sometimes you may also need to add a reference #include

2, Unicode under char * conversion to CString

Method one: Using Api:multibytetowidechar for conversion

char * pfilename = "d://in-school project//qq.bmp";

Calculates the size of the char * array, in bytes, with a Chinese character of two bytes
int charlen = strlen (pfilename);

Calculates the size of multibyte characters, calculated by character.
int len = MultiByteToWideChar (cp_acp,0,pfilename,charlen,null,0);

Request space for a wide-byte character array, size of multibyte characters by byte
TCHAR *buf = new Tchar[len + 1];

Multi-byte encoding converted to wide byte encoding
MultiByteToWideChar (Cp_acp,0,pfilename,charlen,buf,len);

Buf[len] = '/0 '; Add end of string, note not len+1

Converts the TCHAR array to CString
CString Pwidechar;
Pwidechar.append (BUF);

Delete buffer
delete []buf;

Method Two: Use function: a2t, a2w

char * pfilename = "d://in-school project//qq.bmp";

Uses_conversion;
CString s = a2t (pfilename);

CString s = a2w (pfilename);

Method Three: Use the _t macro to convert a string to a wide character

Multibyte character sets, VC6 and VC7 can be compiled through statements, but VS2005 cannot pass, default to Unicode character set
AfxMessageBox ("Load data Failed", 0);

The writing code uses text ("") or _t (""), and the text is common in both Unicode and non-Unicode programs
AfxMessageBox (_t ("Load Data Failed"), 0);

Note: Direct conversion is possible on MBCS projects, but direct conversion is not feasible in projects based on Unicode character sets, CString will save data in Unicode form, forcing type conversions to return only the first character.



CString and int convert to each other

Unicode is only supported under EVC, so the method is as follows:
CString to int:
CString strmytry = _t ("123");
int imytry =-1;
SWSCANF (strmytry,_t ("%d"), &imytry);

int to CString:
int imytry =-1;
CString strmytry = _t ("");
Strmytry.format (_t ("%d"), imytry);



sscanf, swscanf function explanation

Read formatted data from a string.


int sscanf (const char *buffer, const char *format [, argument] ...);
int swscanf (const wchar_t *buffer, const wchar_t *format [, argument] ...);

-----------------------------------------------------------

Cstrin to the _bstr_t method.
CString cs= "AAA";
_bstr_t BSTR = cs. AllocSysString ();

--------------------------------------------------------------------------------
Reader level: Beginner

Friends who have just contacted VC programming are often puzzled by the conversion of many data types, and 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[]= "woman chivalrous Cheng Peijun";
Char temp[200];
Char *buf;
CString str;
_variant_t v1;
_bstr_t v2;

One, other data types converted to strings

short integer (int)
Itoa (i,temp,10);///converts i to a string into the temp, and the last number represents the decimal
Itoa (i,temp,2); Convert in binary mode
Long integer
Ltoa (l,temp,10);


second, get a pointer to the string from another variable containing a string

CString variable
str = "2008 Beijing Olympics";
BUF = (LPSTR) (LPCTSTR) str;
_variant_t variable of BSTR type
V1 = (_bstr_t) "Programmer";
BUF = _com_util::convertbstrtostring ((_bstr_t) v1);

Third, string conversion to other data types

strcpy (temp, "123");

short integer (int)
i = atoi (temp);
Long integer
L = ATOL (temp);
Floating point (double)
D = atof (temp);

Iv. Conversion of other data types to CString


Use the CString member function format to convert, for example:


Integer (int)
Str. Format ("%d", I);
Floating-point number (float)
Str. Format ("%f", I);
Data types that have been supported by CString constructors, such as String pointers (char *), can be directly assigned
str = username;

v. BSTR, _bstr_t and CComBSTR


CComBSTR, _bstr_t is the encapsulation of BSTR, BSTR is a 32-bit pointer to a string.
char * conversion to BSTR can be this way: BSTR b=_com_util::convertstringtobstr ("Data"),///need to add header file before use Comutil.h
Conversely, Char *p=_com_util::convertbstrtostring (b) can be used;


vi. variants, _variant_t and COleVariant


The structure of a variant can refer to the header file Vc98/include/oaidl. The definition of tagvariant in the structure body in H.
Assignment for Variant variables: First assign values to VT members, indicate data types, and assign values to variables of the same data type in the federated structure, for example:
VARIANT va;
int a=2001;
va.vt=vt_i4;///indicates integer data
Va.lval=a; assigning values

For a variant that does not immediately assign a value, it is best to use void VariantInit (Variantarg far* Pvarg) for initialization, which essentially sets VT to VT_EMPTY, and the following table lists the corresponding relationships between VT and commonly used 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 SCODE; Vt_error.
CY Cyval; Vt_cy.
Date 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* far* Ppunkval; Vt_byref| Vt_unknown.
IDispatch far* far* Ppdispval; Vt_byref| Vt_dispatch.
SAFEARRAY far* 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 a Variant wrapper class whose assignment can use coercion type conversions whose constructors automatically process the data types.
Need to add #include when using
For example:
Long l=222;
ing i=100;
_variant_t lval (L);
Lval = (long) i;


The use of COleVariant is basically the same as the _variant_t method, please refer to the following example:
COleVariant v3 = "string", V4 = (long) 1999;
CString str = (BSTR) v3.pbstrval;
Long i = v4.lval;

Vii. Other

In the processing of messages, we often need to decompose 32-bit data (DWORD) such as wparam or lparam into two 16-bit data (WORD), for example:
LPARAM LPARAM;
WORD Lovalue = LoWord (LParam);///take a 16-digit low
WORD Hivalue = HiWord (LParam);///16-digit height
For 16-bit data (WORD) we can use the same method to decompose into two 8-bit data (BYTE), for example:
WORD Wvalue;
BYTE Lovalue = Lobyte (wvalue);///Low 8 digits
BYTE Hivalue = Hibyte (wvalue);///8-digit Height

Strdata.format ("%.NLF", data);
n is a decimal number



BSTR, char* and CString conversions

(1) char* converted into CString

If the char* is converted into CString, the Cstring::format can be used in addition to the direct assignment. For example:

View Plaincopy to Clipboardprint?
Char charray[] = "This is a test";
char * p = "This is a test";
Char charray[] = "This is a test";
char * p = "This is a test";

Or

View Plaincopy to Clipboardprint?
LPSTR p = "This is a test";
LPSTR p = "This is a test";

Or in a program that has a Unicode application defined

View Plaincopy to Clipboardprint?
TCHAR * p = _t ("This is a Test");
TCHAR * p = _t ("This is a Test");

Or

View Plaincopy to Clipboardprint?
LPTSTR p = _t ("This is a Test");
CString thestring = Charray;
Thestring.format (_t ("%s"), Charray);
TheString = p;
LPTSTR p = _t ("This is a Test");
CString thestring = Charray;
Thestring.format (_t ("%s"), Charray);
TheString = p;

(2) CString converted into char*

If you convert a CString class to a char* (LPSTR) type, you often use the following three methods:

Method one, using the cast. For example:

View Plaincopy to Clipboardprint?
CString TheString ("This is a Test");
LPTSTR lpsz = (LPTSTR) (LPCTSTR) thestring;
CString TheString ("This is a Test");
LPTSTR lpsz = (LPTSTR) (LPCTSTR) thestring;

Method two, using strcpy. For example:

View Plaincopy to Clipboardprint?
CString TheString ("This is a Test");
LPTSTR lpsz = new Tchar[thestring.getlength () +1];
_tcscpy (Lpsz, thestring);
CString TheString ("This is a Test");
LPTSTR lpsz = new Tchar[thestring.getlength () +1];
_tcscpy (Lpsz, thestring);

It is necessary to note that the second parameter of the strcpy (or Unicode/mbcs _tcscpy) is either const wchar_t* (Unicode) or const char* (ANSI), which will be converted automatically by the system compiler.

Method three, using Cstring::getbuffer. For example:

View Plaincopy to Clipboardprint?
CString s (_t ("This is a Test"));
LPTSTR p = s.getbuffer ();
Add the code to use p here
if (P!= NULL) *p = _t ('/0 ');
S.releasebuffer ();
Released in time after use so that other CString member functions can be used
CString s (_t ("This is a Test"));
LPTSTR p = s.getbuffer ();
Add the code to use p here
if (P!= NULL) *p = _t ('/0 ');
S.releasebuffer ();
Released in time after use so that other CString member functions can be used

(3) BSTR converted into char*

Method one, using Convertbstrtostring. For example:

View Plaincopy to Clipboardprint?
#include
#pragma comment (lib, "Comsupp.lib")
int _tmain (int argc, _tchar* argv[]) {
BSTR Bstrtext =:: SysAllocString (L "Test");
char* lpszText2 = _com_util::convertbstrtostring (Bstrtext);
SysFreeString (Bstrtext); Use out of release
Delete[] LPSZTEXT2;
return 0;
}
#include
#pragma comment (lib, "Comsupp.lib")
int _tmain (int argc, _tchar* argv[]) {
BSTR Bstrtext =:: SysAllocString (L "Test");
char* lpszText2 = _com_util::convertbstrtostring (Bstrtext);
SysFreeString (Bstrtext); Use out of release
Delete[] LPSZTEXT2;
return 0;
}

Method two, using the _bstr_t assignment operator overload. For example:

View Plaincopy to Clipboardprint?
_bstr_t B = bstrtext;
char* lpszText2 = b;
_bstr_t B = bstrtext;
char* lpszText2 = b;

(4) char* converted into BSTR

Method one, using API functions such as SysAllocString. For example:

View Plaincopy to Clipboardprint?
BSTR Bstrtext =:: SysAllocString (L "Test");
BSTR Bstrtext =:: SysAllocStringLen (L "Test", 4);
BSTR Bstrtext =:: SysAllocStringByteLen ("Test", 4);
BSTR Bstrtext =:: SysAllocString (L "Test");
BSTR Bstrtext =:: SysAllocStringLen (L "Test", 4);
BSTR Bstrtext =:: SysAllocStringByteLen ("Test", 4);

Method two, using COleVariant or _variant_t. For example:

View Plaincopy to Clipboardprint?
COleVariant Strvar ("This is a Test");
_variant_t Strvar ("This is a Test");
BSTR bstrtext = Strvar.bstrval;
COleVariant Strvar ("This is a Test");
_variant_t Strvar ("This is a Test");
BSTR bstrtext = Strvar.bstrval;

Method three, using _bstr_t, this is one of the simplest methods. For example:

View Plaincopy to Clipboardprint?
BSTR Bstrtext = _bstr_t ("This is a Test");
BSTR Bstrtext = _bstr_t ("This is a Test");

Method four, using CComBSTR. For example:

View Plaincopy to Clipboardprint?
BSTR Bstrtext = CComBSTR ("This is a Test");
BSTR Bstrtext = CComBSTR ("This is a Test");

Or

View Plaincopy to Clipboardprint?
CComBSTR BSTR ("This is a Test");
BSTR bstrtext = bstr.m_str;
CComBSTR BSTR ("This is a Test");
BSTR bstrtext = bstr.m_str;

Method five, using CONVERTSTRINGTOBSTR. For example:

View Plaincopy to Clipboardprint?
char* lpsztext = "Test";
BSTR Bstrtext = _com_util::convertstringtobstr (lpsztext);
char* lpsztext = "Test";
BSTR Bstrtext = _com_util::convertstringtobstr (lpsztext);

(5) CString converted into BSTR

This is usually done by using cstringt::allocsysstring. For example:

View Plaincopy to Clipboardprint?
CString Str ("This is a Test");
BSTR bstrtext = str. AllocSysString ();
...
SysFreeString (Bstrtext); Use out of release
CString Str ("This is a Test");
BSTR bstrtext = str. AllocSysString ();
...
SysFreeString (Bstrtext); Use out of release

(6) BSTR converted into CString

Generally, the following methods are available:

View Plaincopy to Clipboardprint?
BSTR Bstrtext =:: SysAllocString (L "Test");
CStringA str;
Str. Empty ();
str = Bstrtext;
BSTR Bstrtext =:: SysAllocString (L "Test");
CStringA str;
Str. Empty ();
str = Bstrtext;

Or

View Plaincopy to Clipboardprint?
CStringA str (bstrtext);
CStringA str (bstrtext);

(7) conversion between ANSI, Unicode, and wide characters

Method One, use MultiByteToWideChar to convert ANSI characters to Unicode characters, and use WideCharToMultiByte to convert Unicode characters to ANSI characters.

Method Two, use "_t" to convert ANSI to a "generic" type string, convert ANSI to Unicode using "L", and use S to convert an ANSI string to a string* object in a managed C + + environment. For example:

View Plaincopy to Clipboardprint?
TCHAR tstr[] = _t ("This is a Test");
wchar_t wszstr[] = L "This is a test";
string* str = S "This is a test";
TCHAR tstr[] = _t ("This is a Test");
wchar_t wszstr[] = L "This is a test";
string* str = S "This is a test";

Method Three, using the conversion macros and classes of ATL 7.0. ATL7.0 has refined and added a number of string conversion macros based on the original 3.0 and provided the corresponding classes, which have the uniform form shown in Figure 3:

Where the first C represents "class" for the purpose of distinguishing between ATL 3.0 macros, the second C represents a constant, and 2 is "to", and the ex indicates a buffer of a certain size. SourceType and destinationtype can be a, T, W, and OLE, meaning ANSI, Unicode, general type, and OLE strings, respectively. For example, CA2CT is a string constant that converts ANSI to a generic type. Here are some sample code:

View Plaincopy to Clipboardprint?
LPTSTR tstr= ca2tex<16> ("This is a Test");
LPCTSTR tcstr= ca2ct ("This is a Test");
wchar_t wszstr[] = L "This is a test";
char* chstr = cw2a (WSZSTR);
LPTSTR tstr= ca2tex<16> ("This is a Test");
LPCTSTR tcstr= ca2ct ("This is a Test");
wchar_t wszstr[] = L "This is a test";
char* chstr = cw2a (WSZSTR);

Conclusion

Almost all programs use strings, and Visual C + +. NET is powerful and widely used, so the conversion between strings is more frequent. This article covers almost all of the current conversion methods. Of course, for. NET Framework, you can also use the Convert and text classes to convert between different data types and character encodings.


CString Conversion Issues

_bstr_t and CString convert to each other

_bstr_t BSTR;
CString strSQL;
CString-> _bstr_t:bstr = (_bstr_t) strSQL;
_bstr_t-> cstring:strsql = (LPCSTR) BSTR;



BSTR wide strings and CString convert to each other

BSTR BSTR;
CString strSQL;
CString-> bstr:bstr = strsql.allocsysstring ();
BSTR-> cstring:strsql = (LPCSTR) BSTR;



1, _variant_t --> -->

(1), generally passed to these 3 pointers are not directly supported by MFC data types, but to use _variant_t conversion
_variant_t (XX) can convert most types of variables into appropriate types for incoming:
(2), _variant_t var;_variant_t-> Long: (long) var;
_variant_t-> cstring:cstring strvalue = (LPCSTR) _bstr_t (VAR);
CString-> _variant_t: _variant_t (strSQL);



Conversion between the cstring,int,string,char*
String Turn CString
Cstring.format ("%s", String.c_str ());

Char Turn CString
Cstring.format ("%s", char*);

Char Turn string
string S (char *);

String char *
Char *p = STRING.C_STR ();

CString Turn string
String s (Cstring.getbuffer ());

1,string-> CString

Cstring.format ("%s", String.c_str ());
Using C_str () is indeed better than data ().
2,char-> String
string S (char *);
Your can only initialize, in the place that does not initialize is best still use assign ().
3,cstring-> String
String s (Cstring.getbuffer ());
GetBuffer () must be releasebuffer (), otherwise there is no space to free the buffer.


In the C + + standard library of functions.
There are three functions that can convert the contents of a string into character arrays and c-string
1.data (), returns an array of strings without "/0"
2,C_STR (), returns an array of strings with "/0"
3,copy ()


CString Cross int

Converts a character to an integer, and you can use Atoi, _atoi64, or ATOL.
To convert a number to a CString variable, you can use the CString format function. Such as
CString s;
int i = 64;
S.format ("%d", i)
The Format function is very powerful and worth studying.

void Cstrdlg::onbutton1 ()
{
Todo:add your control notification handler code here
CString
Ss= "1212.12";
int Temp=atoi (ss);
CString AA;
Aa. Format ("%d", temp);
AfxMessageBox ("var is" + AA);
}

Sart. Format ("%s", buf);

CString Mutual Turn char*

char * to CString
CString strtest;
char * CHARPOINT;
Charpoint= "Give string a value";
Strtest=charpoint;


CString to char *
Charpoint=strtest. GetBuffer (strtest. GetLength ());

There is no String,char *==char in standard C []==string

You can use the Cstring.format ("%s", char *) method to turn char * to CString. To convert the CString to char *, use the operator (LPCSTR) to CString it.


CString conversion char[100]

Char a[100];
CString Str ("aaaaaa");
strncpy (A, (LPCTSTR) str,sizeof (a));
2 conversion of CString type to int
Convert CString type to int
Converts a character to an integer, and you can use Atoi, _atoi64, or ATOL.

CString AAA = "16";
int int_chage = Atoi ((LPCSTR) AAA);


To convert a number to a CString variable, you can use the CString format function. Such as
CString s;
int i = 64;
S.format ("%d", i)
The Format function is very powerful and worth studying.
If you are using a char array, you can also use the sprintf function.

CString ss= "1212.12";
int Temp=atoi (ss);
CString AA;
Aa. Format ("%d", temp);


Digital-> strings are Cstring::format, FORMATV, sprintf and AFX Itoa

3 char* in the loading int

#include

int atoi (const char *nptr);
Long Atol (const char *nptr);
Long Long Atoll (const char *nptr);
Long Long Atoq (const char *nptr);

4 Conversion between the cstring,int,string,char*

String AA ("AAA");
Char *c=aa.c_str ();


Cannot convert from ' const char * ' to ' char * '
const char *C=AA.C_STR ();

5 conversion between the cstring,int,string,char*

STRING.C_STR () can only be converted to const char *,
To convert to char * This writes:

String Mngname;
Char t[200]; memset (t,0,200); strcpy (T,mngname.c_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.