convert a std::string to const char* or char*
2017-05-09 00:00
351 查看
If you just want to pass a
If you want to get a writable copy, like
Edit: Notice that the above is not exception safe. If anything between the
std::stringto 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 it delete[] writable;
Edit: Notice that the above is not exception safe. If anything between the
newcall and the
deletecall throws, you will leak memory, as nothing will call
deletefor you automatically. There are two immediate ways to solve this.
boost::scoped_array
boost::scoped_arraywill 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 usestd::vector, which completely manages the memory for you.
std::string str; std::vector<char> writable(str.begin(), str.end()); writable.push_back('\0'); // get the char* using &writable[0] or &*writable.begin()
相关文章推荐
- Convert std::string to const char* or char*
- cannot convert parameter 1 from 'std::string' to 'const char *'
- [C# Tip]How to: Convert System::String to wchar_t* or char*
- Convert std::string to std::wstring or LPCWSTR
- C++编译出现binding ‘const string {aka const std::__cxx11::basic_string<char>}’ to reference of type ‘std
- amule: FTBFS ("cannot convert 'UpnpString* {aka s_UpnpString*}' to 'const char*'")
- string转Char*( error C2440: '=' : cannot convert from 'const char *' to 'char *')
- How to convert std::string to LPCWSTR in C++ (Unicode)
- Convert asio::streambuf to std::string
- 报错 error C2664: 'CreateWindowExA' : cannot convert parameter 2 from 'unsigned short [10]' to 'const char *'
- c++ int convert to std::string 转换成std::string
- Convert a String In C++ To Upper or Lower Case
- How to convert QString to std::string?
- C# How to Convert String to ASCII OR how to convert ASCII To String
- 【求助】 no matching function for call to `strcpy(std::string&, char*&)'
- error: no matching function for call to 'std::basic_ifstream<char>::open(std::string&)
- error C2664: 'atoi' : cannot convert parameter 1 from 'CString' to 'const char *'
- cannot convert wchar_t to const char*
- convert between char* and std::string
- cannot convert from 'const int' to 'const char *'