Convert std::string to const char* or char*
来源:互联网 发布:租车软件排行知乎 编辑:程序博客网 时间:2024/05/21 19:21
Q:
How can I convert an std::string
to a char*
or a const char*
?
A:
If you just want to pass a std::string
to a function that needs const char*
you can use
std::string str;const char * c = str.c_str();
If you want to get a writable copy, like char *
, you can do that with this:
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 itdelete[] writable;
Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.
boost::scoped_array
boost::scoped_array
will delete the memory for you upon going out of scope:
std::string str;boost::scoped_array<char> writable(new char[str.size() + 1]);std::copy(str.begin(), str.end(), writable.get());writable[str.size()] = '\0'; // don't forget the terminating 0// get the char* using writable.get()// memory is automatically freed if the smart pointer goes // out of scope
std::vector
This is the standard way (does not require any external library). You use std::vector
, which completely manages the memory for you.
std::string str;std::vector<char> writable(str.size() + 1);std::copy(str.begin(), str.end(), writable.begin());// get the char* using &writable[0] or &*writable.begin()
From:http://stackoverflow.com/questions/347949/convert-stdstring-to-const-char-or-char
- Convert std::string to const char* or char*
- cannot convert parameter 1 from 'std::string' to 'const char *'
- std::string to char*
- [C++]char* const char* std::string区分
- How to: Convert System::String to wchar_t* or char*
- string转Char*( error C2440: '=' : cannot convert from 'const char *' to 'char *')
- 关于编译报错 error: cannot convert ‘const std::__cxx11::basic_string’ to ‘const char*’ 的处理
- 关于编译报错 error: cannot convert 'const std::__cxx11::basic_string<char>' to 'const char*' 的处理
- std::string 转换为 const* char
- Cannot convert from 'const char [..]' to 'LPCTSTR'
- Cannot convert from 'const char [..]' to 'LPCTSTR'
- cannot convert wchar_t to const char*
- E2034 Cannot convert 'wchar_t *' to 'const char *'
- Convert Between char* string to wchar_t* string
- How to convert InputStream to String/convert char[] to String
- const char* to char*
- std::__stl_throw_length_error(char const*)
- char* convert to string and back
- 相同端口的UDP套接字数量过多导致软中断占用CPU利用率高的原因分析
- STM32F103的GPIO 模式区分
- 跳台阶
- 推荐视频反馈系统设计
- ole接口
- Convert std::string to const char* or char*
- phonegap
- java中引用和对象区别
- 一个Java小程序
- 黑马程序员----Object类
- Ubuntu12.04 用MentoHUST认证上网提示“打开libnotify失败,请检查是否已安装该库文件”解决方案
- 使用LCP建立链路
- SQL查询包含指定列的所有表
- c++自定义类实现MFC中IsKindOf功能