1. string -> CString
CString cs;
string s("abc");
cs.Format("%s",s.c_str());
2.string -> const char*
string s("abc");
const char* c = s.c_str();
c_str()函数返回的是一个指向C格式字符串的常指针,c++ primer中说,把一个const对象的地址赋给一个普通的、非const对象的指针会导致编译错误,但允许把非const对象的地址赋给指向const对象的指针。所以必须左操作符必须是一个指向const对象的指针。
3.string -> char*
string source = "abcdefg";
int length = strlen(source.c_str());
char *s = new char[length+1];
memset(s,0,length+1);
strcpy(s,source.c_str());
cout << s << endl;
delete []s;
这时动态分配内存
4.string -> char[]
string source = "abcdefg";
char charArray[10];
memset(charArray,0,10);
strcpy(charArray,source.c_str());
cout<<charArray<<endl;
5.string -> int
string source = "12";
int a = atoi(source.c_str());
cout << a <<endl;
6.char buffer[row] -> string
char buffer[10] = {"abcdefg"};
string source(buffer);
cout << source << endl;
7.char buffer[row][line] -> string
char buffer[2][10] = {"abcd","asdf"};
char buf[20];
strcpy(buf,buffer[0]);
strcat(buf,buffer[1]);
string source(buf);
cout << source << endl;
8.int(float...) ->string
char buffer[20];
int i = 3445;
itoa( i, buffer, 10 );
string s(buffer);
cout<< s << endl;
char buffer[20];
int i = 3445;
sprintf(buffer,"%d",i);
string s(buffer);
cout << s << endl;
//stringstream( )的头文件<sstream.h>
int i = 3445;
stringstream ss;
ss<<i;
string s = ss.str();
cout << s << endl;
9.CString -> string
CString str;
string buffer(str);
//或者
CString str;
string str(str.GetBuffer());
str.releaseBuffer();
10.char -> string
char c = 'a';
string s(1,c);
cout << s << endl;
11.char* -> string
char* ss = "abddas";
string s(ss);
cout << s << endl;
12.char[] -> string
char a[] = "adfadsf";
string s(a);
cout << s << endl;