std::string 转换为 const* char
2013-04-18 11:12
363 查看
std::string 转换为 const* char,方式如下:
std::string str;
const char * c = str.c_str();
如果需要转换为一个可变char,做法如下:
std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;
需要说明的是,上面的这个方法并不是非常安全,在新的调用和被删除之前有可能会导致内存泄露。解决的方法有两个,使用boost::scoped_array或者std::vector采用copy的方式进行重新构建。
std::string str;
const char * c = str.c_str();
如果需要转换为一个可变char,做法如下:
std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;
需要说明的是,上面的这个方法并不是非常安全,在新的调用和被删除之前有可能会导致内存泄露。解决的方法有两个,使用boost::scoped_array或者std::vector采用copy的方式进行重新构建。
相关文章推荐
- std::string ,QString和const char * 的互相转换
- VS2010不能将参数 1 从“std::string”转换为“const char *”解决
- VS2010不能将参数 1 从“std::string”转换为“const char *”解决
- VS2013不能将参数 1 从“std::string”转换为“const char *”解决
- ANSI与UTF-8编码互相转换,CString,std::string,char*,const char*互相转换
- VS2010不能将参数 1 从“std::string”转换为“const char *”解决
- std::string , Qstring和 const char * 的互相转换
- VS2010不能将参数 1 从“std::string”转换为“const char *”解决
- 如何解决error C2664: “atof”: 不能将参数 1 从“std::string”转换为“const char *”
- cocos2d-x 关于 std::string 与 const char* 之间转换的奇怪问题
- 如何从string 转换为const char *和char * (附带string中c_str()、data()、copy(p,n)函数的用法)
- string,const char*,char*之间的相互转换
- char*,const char*和string 三者转换
- "std::basic_stringbuf<char, std::char_traits<char>, std::allocator<char> >::str() const"问题的解决办法
- C++ char*,const char*,string的相互转换
- char*,const char*和string的相互转换
- c++中的一些类型转换 : CString,string,int ,long,double,char*,const char*,date等
- 怎么把webkit中的AtomicString转换成const char*
- const char* char*和string之间的转换
- 一个将string转换为 const* char的函数