C++(MFC)中的常见类型转换
1.string 和 CString间的转换。
string 转 CString
string str = "Hello World";
CString cStr;
cStr = str.c_str();//c_str()生成以'\0'结尾的字符串
CString 转 string
CString cStr = "Hello World";
string str;
str = cStr.getBuffer(0);//为一个CString字符串重新获得其缓冲区内容
2.char*、const char* 和 string间的转换。
string 转 const char*
string str = "Hello World";
const char* cChar = str.c_str();//利用c_str()
const char* 转 string
const char* cChar = "Hello World";
string str = cChar;//直接赋值即可
const char* 转 char*
const char* cChar = "Hello World";
char* mChar = const_cast<char*>(cChar);//利用const_cast<>
char* 转 const char*
char* mChar = "Hello World";
const char* cChar = mChar;//直接赋值
string 转 char*
string str = "Hello World";
char* mChar = const_cast<char*>(str.c_str());//两次变换
char* 转 string
char* mChar = "Hello World";
string str = mChar;//直接赋值
3.string 和 int间的转换。
string 转 int
string str = "0";
int num = atoi(str.c_str());//利用atoi
int 转 string
int num = 0;
stringstream ss;
ss << num ;
string str = ss.str(); //利用数据流
#针对其他数据类型转换string,参考 Mike_Zhang提供的模板类
/*
convert other data to string
usage :
string str = m_toStr<int>(12345);
*/
template <class T> string m_toStr(T tmp)
{
stringstream ss;
ss << tmp;
return ss.str();
}
int转string时,习惯先将int转为char[]
char charStr[8];
int num = 521;
itoa(num, charStr, 10);//利用itoa
string str = charStr;