C++中常见类型转换

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;




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值