c++字符串互相转换

浏览: 47 发布日期: 2017-07-01 分类: c++

此篇文章将要介绍c++字符串互相转换的说明,具体操作请看面的内容

1.string vs char*

//string to char*
string str;
const char* cch = str.c_str();
char *ch = new char[strlen(cch)+1];
strcpy(ch,cch);

//char* to string
string str = ch;

2.string vs CString

//CString to string
CString cstr;
string str = CStringA(cstr); 

//string to CString
CString cstr = CString(str.c_str());

3.CString vs char*

//CString to char*
CString cstr;
int len = WideCharToMultiByte(CP_ACP, 0, cstr, -1, NULL, 0, NULL, NULL);
char *ch = new char[len + 1];
WideCharToMultiByte(CP_ACP, 0, cstr, -1, ch, len, NULL, NULL);

//char* to CString
CString cstr = CString(ch);

4.int vs string

//采用c++11新增函数stoi,stof,stol,to_string等进行数值与string之间的转换
//string to int
string str = “111”;
int i = stoi(str);      

//int to string
string str = to_string(i);

本文只提供了很多种转换方法中的一种,亲测有效!

以上就是这篇文章的全部内容了,希望大家能够喜欢。

返回顶部