Most of the definitions of strings in MFC use the cstring class. It is inevitable that strings of the cstring type need to be converted to integer or other types of variables. This problem was encountered in a recent project.
Cstring is used to define a string consisting of digits, but it must be converted to a byte type. It is easy to think of the atoi function. The main function of the atoi function is to convert a string to an integer. The function prototype is as follows:
[Code] int atoi (const char * string); [/Code]
We can see that the parameter of the function is const char *, and the direct conversion in the VC 6.0 environment has no problem.
[Code] int n = atoi (STR) [/Code]
However, if the same code is used in the vs2008 environment, an error is reported, promptingW_char * cannot be converted to _ char *. Because I checked unicode encoding when creating a project.
Cause analysis:
In Visual C ++ net, the default character set format is Unicode. In vc6.0, the default character set format is multi-byte character set (MBCS, multi-byte character set ), this leads to various types of character operations and functions that are very simple and practical in vc6.0, which may cause various errors when running in the vs environment. The following describes how to convert cstring and char * in the Unicode Character Set in vs environment, that is, to convert the Unicode Character Set and the MBCS character set.
- Conversion of cstring to char * in Unicode *
(1) Use Windows API: widechartomultibyte for conversion
From the function name, we can see that the function converts Unicode-encoded widechar to multi-byte characters. For details, refer to msdn. Its definition is as follows: [Code] int widechartomultibyte (Uint codePage,
DWORD dwflags,
Lpcwstr lpwidecharstr,
Int cchwidechar,
Lpstr lpmultibytestr,
Int cbmultibyte,
Lpstr lpdefaultchar,
Lpbool lpuseddefaultchar
);
[/Code]
The third parameter lpwidecharstr is the width string to be converted, and the fourth ParameterCchwidecharThe length of the string to be converted. The fifth parameter, lpmultibytestr, indicates the converted multi-byte string pointer. The sixth parameter, cbmulibyte, indicates the length (in bytes) of the converted multi-byte string ). The Return Value of the function is described as follows: returns the number of bytes written to the buffer pointed to
LpmultibytestrIf successful; if the function succeeds andCbmultibyteIs 0, the return value is the required size, in bytes, for the buffer indicated
Lpmultibytestr. The function returns 0 if it does not succeed. The following example is from the network.
[Code] cstring STR = _ T ("(" D: \ internal project \ qq.bmp ")
Int n = Str. getlength (); // n = 14. n is the string length obtained by character. Both Chinese and English characters are counted as one character.
// Obtain the length of a Multi-byte string, measured in bytes. The Chinese Character occupies two bytes.
Int Len = widechartomultibyte (cp_acp, 0, STR, str. getlength (), null, 0, null, null) // For the above example Len = 18, because the Chinese character occupies 2 bytes
// Apply for space for multi-byte characters. The array size is the string length calculated in bytes. Note that the string must end with \ 0.
Char * P = new char [Len + 1]
// Convert a wide string to a multi-byte encoded string
Widechartomultibyte (cp_acp, 0, STR, str. getlength (), P, Len, null, null );
P [Len + 1] = '\ 0 '; // <strong> the string ending with \ 0 should be stored in P [Len] instead of Len + 1 </strong> [/Code]
(2) Use macro T2A or w2a
The Code is as follows:
[Code]
Cstring STR = _ T ("(" D: \ internal project \ qq.bmp ");
// Declare the identifier, which cannot be forgotten; otherwise, the compiler reports an error.
Uses-conversion;
// Call the function. T2A and w2a both support character conversion in ATL and MFC.
Char * P = T2A (STR );
// Char * P = w2a (STR); // conversion is also possible
[/Code]
Note: Sometimes you may need to add reference # include <afxpriv. h> // the original text is copied.
- Convert char * in Unicode to cstring
(1) Use API: multibytetowidechar for conversion
Multibytetowidechar is used to convert a multi-byte string to a wide character in the Unicode environment. Msdn is defined as follows:
[Code]
Int multibytetowidechar (uint codePage,DWORD dwflags,
Lpcstr lpmultibytestr,
Int cbmultibyte,
Lpwstr lpwidecharstr,
Int cchwidechar,
);
[/Code]
The implementation code is as follows:
[Code]
Char * P = "D: \ internal project \ qq.bmp ";
// Calculate the size of the char * array, in bytes. One Chinese Character occupies two bytes.
Int charlen = strlen (P );
// Calculate the size of Multi-byte characters, measured in characters.
Int Len = multibytetowidechar (cp_acp, 0, P, charlen, null, 0 );
// Request space for the wide byte character array. The array size is the size of Multi-byte characters calculated in bytes.
Tchar * Buf = new tchar [Len + 1];
// Convert multi-byte encoding to wide-byte encoding
Multibytetowidechar (cp_acp, 0, P, charlen, Buf, Len );
Buf [Len] = '\ 0'; // Add the end of the string. Note that it is not Len + 1.
// Convert the tchar array to cstring
Cstring pwidechar;
Pwidechar. append (BUF );
// Delete the buffer
Delete [] Buf;
[/Code]
(2) Use the macro a2t or w2a for conversion.
The Code is as follows:
[Code]
Char * pF = "D: \ internal project \ qq.bmp ";
Uses_conversion;
Cstring S = a2t (P );
// Cstring S = a2w (P );
[/Code]
(3) Use a _ t macro to convert a string to a wide character
[Code]
// Multi-byte character set. statements that can be compiled in vc6 and vc7, but cannot be passed in vs2005. The default value is Unicode Character Set.
// Afxmessagebox ("failed to load data", 0 );
// Use text ("") or _ T ("") to write code. The text is common in Unicode and non-Unicode programs.
Afxmessagebox (_ T ("failed to load data"), 0 );
// If it is only in the Unicode environment, you can also use the L macro
STR = l "loading data failed ";
[/Code]
- Summary
Direct conversion is possible in MBCS-based projects, but it does not work in projects based on the Unicode Character Set. cstring stores data in the form of Unicode, and the forced conversion only returns the first character.
- Test code:
Char m_strip [256] = "D: \ 192.168.1.101 ";
Int charlen = strlen (m_strip );
Int Len = multibytetowidechar (cp_acp, 0, m_strip, charlen, null, 0 );
Tchar * Buf = new tchar [Len + 1];
Multibytetowidechar (cp_acp, 0, m_strip, charlen, Buf, Len );
Buf [Len] = '\ 0'; // Add the end of the string. Note that it is not Len + 1.
Cstring pwidechar;
Pwidechar. append (BUF );
Delete [] Buf; // delete a buffer
Cstring cshead (_ T ("D :\\"));
Cstring cstemp (_ T ("\\"));
Char m_strip [256] = "192.168.1.101 ";
Uses_conversion;
Cstring S1 = a2t (m_strip );
S1 = cshead + S1;
Ctime T = ctime: getcurrenttime ();
Char dir [10];
Char filename [20];
Memset (Dir, 0, 10 );
Memset (filename, 0, 20 );
Sprintf (Dir, "% 04d % 02d % 02d", T. getyear (), T. getmonth (), T. getday ());
Int H = T. gethour ();
Int M = T. getminute ();
Int S = T. getsecond ();
Sprintf (filename, "% 02d % 02d % 02d-% 02d % 02d % 02d. Avi", H, M, S, H, M, S + 2 );
Cstring S2 = a2t (DIR );
S2 = S1 + cstemp + S2;
Cstring filepath = a2t (filename );
Filepath = S2 + cstemp + filepath;
Int err;
If (! Createdirectory (S1, null ))
{
If (getlasterror () = error_already_exists)
{
Cout <"already_exists" <Endl;
}
Else
Cout <"error" <Endl;
}
If (! Createdirectory (S2, null ))
{
If (getlasterror () = error_already_exists)
{
Cout <"already_exists" <Endl;
}
Else
Cout <"error" <Endl;
}
Cfile file (filepath, cfile: modecreate | cfile: modereadwrite );
File. Write (m_strip, strlen (m_strip ));
File. Close ();