Conversion between C++ string types and numbers
Reprinted: http://www.cnblogs.com/luxiaoxun/archive/2012/08/03/2621803.html
1. Conversion between string numbers
String ---Character array
(1) string --> char *
string str("OK");
char * p = str.c_str();
Character array---string
(2)char * -->string
char *p = "OK";
string str(p);
Character array---CString
(3)char * -->CString
char *p ="OK";
CString m_Str(p);
//or
CString m_Str;
m_Str.Format("%s",p);
CString---Character array
(4) CString --> 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));
Be sure to ReleaseBuffer after GetBuffer() (), otherwise the space occupied by the buffer is not released, and the CString object cannot grow dynamically.
(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. Number to string: use sprintf() function
string formatting command, the main function is to write formatted data In a string.
Function prototype
int sprintf( char *buffer, const char *format, [ argument] … );
parameter list
buffer: char pointer, pointing to the buffer of the string to be written.
format: format string.
[argument]...: Optional parameters, which can be any type of data.
return value
String length (strlen)
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 hexadecimal is converted to hexadecimal, if the output uppercase letter is sprintf(str,"%X",a)
------------ --------
char *itoa(int value, char* string, int radix);
also can convert numbers to strings, but the function itoa() is platform-dependent (not in the standard), so It is not recommended to use this function here.
3. Convert a string to a number: use the sscanf() function
to read data that matches the specified format from a string.
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); // Hexadecimal is converted to decimal.
In addition, atoi(), atol(), atof() can also be used.
4. Use stringstream class
Use ostringstream object to write a string, similar to sprintf()
ostringstream s1;
int i = 22;
s1 << "Hello "<< i << endl;
string s2 = s1.str();
cout << s2;
read a string with the isringstream object, similar to sscanf()
istringstream stream1;
string string1 = "25";
stream1.str(string1);
int i;
stream1 >> i;
cout << i << endl; // displays 25
Writing code is an art, better than Mona Lisa's smile.
Category: C++ basic concepts