如何在c ++中将字符串转换为char *? [英] How do I convert a string to a char* in c++?

查看:234
本文介绍了如何在c ++中将字符串转换为char *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的程序中有一个错误:无法从字符串转换为字符*。

I have an error in my program: "could not convert from string to char*". How do I perform this conversion?

推荐答案

如果可以解决 const char * ,你只需要调用 c_str()方法:

If you can settle for a const char*, you just need to call the c_str() method on it:

const char *mycharp = mystring.c_str();



如果你真的需要一个可修改的 char * ,您将需要复制字符串的缓冲区。 向量是一种理想的处理方式:

If you really need a modifiable char*, you will need to make a copy of the string's buffer. A vector is an ideal way of handling this for you:

std::vector<char> v(mystring.length() + 1);
std::strcpy(&v[0], mystring.c_str());
char* pc = &v[0];

这篇关于如何在c ++中将字符串转换为char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆