1. string-to-int conversion in c ++
1) in the C standard library, use atoi:
# Include <cstdlib>
# Include <string>
Std: string text = "152 ";
Int number = std: atoi (text. c_str ());
If (errno = ERANGE) // It may be std: errno
{
// The number may be too large or too small to be fully stored
}
Else if (errno == ????)
// It may be EINVAL
{
// Cannot be converted into a number
}
2) use stringstream in the C ++ standard library: (stringstream can be used for conversion between various data types)
# Include <sstream>
# Include <string>
Std: string text = "152 ";
Int number;
Std: stringstream ss;
Ss <text; // other data types
Ss> number; // string-> int
If (! Ss. good ())
{
// Error occurred
}
Ss <number; // int-> string
String str = ss. str ();
If (! Ss. good ())
{
// Error occurred
}
3) In the Boost library, use lexical_cast:
# Include <boost/lexical_cast.hpp>
# Include <string>
Try
{
Std: string text = "152 ";
Int number = boost: lexical_cast <int> (text );
}
Catch (const boost: bad_lexical_cast &)
{
// Conversion failed
}
2. Convert string to CString
CString. format ("% s", string. c_str ());
Using c_str () is indeed better than data;
3. Convert char to CString
CString. format ("% s", char *);
4. Convert char to string
String s (char *);
Only Initialization is allowed. It is best to use assign () instead of initialization ().
5. Convert string to char *
Char * p = string. c_str ();
6. Convert CString to string
String s (CString. GetBuffer ());
ReleaseBuffer () is required after GetBuffer (). Otherwise, no space occupied by the buffer is released.
7. Convert the content of a string to a character array and a C-string
(1) data (), returns a string array without "\ 0"
(2) c_str (), returns a string array with "\ 0"
(3) copy ()
8. Conversion between CString and int, char *, and char [100]
(1) convert CString to int
Converts a character to an integer. You can use atoi, _ atoi64, or atol. To convert a number to a CString variable, you can use the Format function of CString. For example
CString s;
Int I = 64;
S. Format ("% d", I)
The Format function is very powerful and worth your research.
Void CStrDlg: OnButton1 ()
{
CString
Ss = "1212.12 ″;
Int temp = atoi (ss );
CString aa;
Aa. Format ("% d", temp );
AfxMessageBox ("var is" + aa );
}
(2) convert CString to char *
/// Char * TO cstring
CString strtest;
Char * charpoint;
Charpoint = "give string a value ";//?
Strtest = charpoint;
/// Cstring TO char *
Charpoint = strtest. GetBuffer (strtest. GetLength ());
(3) There is no string in Standard C, char * = char [] = string, and CString can be used. format ("% s", char *) to convert char * To CString.
To convert CString to char *, use the operator (LPCSTR) CString.
CString conversion char [100]
Char a [100];
CString str ("aaaaaa ");
Strncpy (a, (LPCTSTR) str, sizeof ());
From the column Leeboy_Wang