Mar*_*rst 28
如果你能满足于const char*,你只需要调用c_str()它上面的方法:
const char *mycharp = mystring.c_str();
Run Code Online (Sandbox Code Playgroud)
如果你真的需要一个可修改的char*,你需要复制字符串的缓冲区.A vector是为您处理此问题的理想方式:
std::vector<char> v(mystring.length() + 1);
std::strcpy(&v[0], mystring.c_str());
char* pc = &v[0];Run Code Online (Sandbox Code Playgroud)
sbi*_*sbi 15
调用str.c_str()以获得const char*:
const char *pch = str.c_str();
Run Code Online (Sandbox Code Playgroud)
请注意,结果const char*仅str在更改或销毁之前有效.
但是,如果你真的需要非const,你可能不应该使用std::string,因为它不是为了允许更改其背后的基础数据而设计的.也就是说,您可以通过调用&str[0]或获取指向其数据的指针&*str.begin().
The ugliness of this should be considered a feature. In C++98, std::string isn't even required to store its data in a contiguous chunk of memory, so this might explode into your face. I think has changed, but I cannot even remember whether this was for C++03 or the upcoming next version of the standard, C++1x.
If you need to do this, consider using a std::vector<char> instead. You can access its data the same way: &v[0] or &*v.begin().
//assume you have an std::string, str.
char* cstr = new char[str.length() +1];
strcpy(cstr, str.c_str());
//eventually, remember to delete cstr
delete[] cstr;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34131 次 |
| 最近记录: |