C++ char * 转字符串
可能的重复:
如何将 char * 复制到字符串中,反之亦然
我必须将一个值传递到需要 char * 的方法中
MyMethod(char * parameter)
{
// code
}
,但是,我需要提供的参数当前是 std::string。如何将 std::string 转换为 char *?
std::string myStringParameter = //whatever
char * myCharParameter = //Convert here somehow
MyMethod(myCharParameter);
Possible Duplicate:
how to copy char * into a string and vice-versa
I have to pass a value into a method that required a char *
MyMethod(char * parameter)
{
// code
}
However, the parameter I need to feed it is currently a std::string. How do I convert the std::string to a char *?
std::string myStringParameter = //whatever
char * myCharParameter = //Convert here somehow
MyMethod(myCharParameter);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找
c_str()
方法:您可能需要对返回进行
const_cast
处理,以将其转换为char *
而不是const char *
。但不要修改字符串;它是std::string
对象的内部缓冲区。如果您确实需要修改字符串,您应该使用strncpy
将其复制到另一个缓冲区:You are looking for the
c_str()
method:You might need to
const_cast
the return to get it into achar *
instead of aconst char *
. Refrain from modifying the string though; it is the internal buffer of thestd::string
object. If you actually need to modify the string, you should usestrncpy
to copy it to another buffer:这取决于 MyMethod 是否实际上更改了传入的字符串。
如果您唯一知道的就是签名,那么您必须假设它可以更改字符串,并根据 @jdmichal 的答案将其复制到临时缓冲区中。
该 API 的开发人员也可能不知道或不关心
const
的正确性。因此,该函数接受一个非 const 缓冲区,即使它不会改变它。如果是这种情况,您可以这样处理:
在我的职业生涯中,我遇到过不少 API 接受本应为
const
的非const
字符串。It depends on whether MyMethod actually changes the string that's passed in.
If the only thing you know about it is the signature, then you have to assume it could change the string, and copy it into a temporary buffer per @jdmichal's answer.
It's also possible that the developer of this API didn't know or care about
const
correctness. So the function takes in a non-const
buffer even though it doesn't change it.If that's the case you can get by with:
In my career I have come across more than a few API's taking in non-
const
strings that should have beenconst
.如果该函数实际上要修改字符串,您最好创建一个单独的副本:
If the function is actually going to modify the string, you'd better create a separate copy: