1. Conversion between string numbers
(1) string---char *
String str ("OK");
char * p = str.c_str ();
(2) char *-->string
Char *p = "OK";
String str (p);
(3) char *-->cstring
Char *p = "OK";
CString m_str (P);
Or
CString m_str;
M_str.format ("%s", p);
(4) CString to char *
CString Str ("OK");
char * p = str. GetBuffer (0);
...
Str. ReleaseBuffer ();
(5) string--CString
Cstring.format ("%s", String.c_str ());
(6) CString--string
String s (Cstring.getbuffer (0));
GetBuffer () must be releasebuffer (), otherwise there is no space to release the buffer, CString objects cannot be dynamically increased.
(7) Double/float->cstring
Double data;
Cstring.format ("%.2f", data); Keep 2 decimal places
(8) Cstring->double
CString s= "123.12";
Double D=atof (s);
(9) String->double
Double D=atof (S.c_str ());
2. Numeric to String: Use sprintf () function
Char str[10];
int a=1234321;
sprintf (str, "%d", a);
--------------------
Char str[10];
Double a=123.321;
sprintf (str, "%.3LF", a);
--------------------
Char str[10];
int a=175;
sprintf (str, "%x", a),//10 conversion into 16, if the output uppercase letter is sprintf (str, "%x", a)
--------------------
char *itoa (int value, char* string, int radix);
It is also possible to convert a number to a string, but itoa () is a platform-dependent (not standard) function, so it is not recommended here.
3. String to number: using the sscanf () function
Char str[]= "1234321";
int A;
SSCANF (str, "%d", &a);
.............
Char str[]= "123.321";
Double A;
SSCANF (str, "%LF", &a);
.............
Char str[]= "AF";
int A;
SSCANF (str, "%x", &a); 16 binary converted to 10 binary
Alternatively, you can use Atoi (), Atol (), Atof ().
4. Using StringStream class
Write a string with the Ostringstream object, similar to sprintf ()
Ostringstream S1;
int i = 22;
S1 << "Hello" << i << Endl;
String s2 = S1.str ();
cout << S2;
Reads a string with the Istringstream object, similar to SSCANF ()
Istringstream stream1;
String string1 = "25";
STREAM1.STR (string1);
int i;
Stream1 >> i;
cout << i << Endl; Displays 25
Conversion of numbers and strings in C + +