将 std::string 转换为 char * 替代方案
我在谷歌中进行了搜索,并被告知这是不可能的,因为我只能从字符串中获取静态 char *
,所以我正在寻找替代方案。
情况如下: 我有一个 .txt 文件,其中包含其他 .txt 文件和一些数字的列表,这样做是为了可以添加程序而无需重新编译。我使用 ifstream
将文件名读入字符串。
它们所需的函数需要一个 char *
而不是 string
,显然这种转换是不可能的。
我可以访问此函数,但它使用 char *
调用另一个函数,因此我认为我无法使用 char *
。
有谁知道解决方法或其他方法吗?
I have done a search in google and been told this is impossible as I can only get a static char *
from a string, so I am looking for an alternative.
Here is the situation:
I have a .txt file that contains a list of other .txt files and some numbers, this is done so the program can be added to without recompilation. I use an ifstream
to read the filenames into a string.
The function that they are required for is expecting a char *
not a string
and apparently this conversion is impossible.
I have access to this function but it calls another function with the char *
so I think im stuck using a char *
.
Does anyone know of a work around or another way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 C++ 中,如果需要非 const char* ,我总是会执行以下操作:
第一行创建字符串的可修改副本,保证驻留在一个连续的内存块。第二行获取指向该缓冲区开头的指针。请注意,向量比字符串大一个元素,以适应空终止。
In C++, I’d always do the following if a non-
const
char*
is needed:The first line creates a modifiable copy of our string that is guaranteed to reside in a contiguous memory block. The second line gets a pointer to the beginning of this buffer. Notice that the vector is one element bigger than the string to accomodate a null termination.
您可以使用
c_str
获取字符串的const char*
:如果您只需要一个 char*,则必须制作一个副本,例如执行以下操作:
You can get a
const char*
to the string usingc_str
:If you need just a char* you have to make a copy, e.g. doing:
正如之前的海报所提到的,如果被调用的函数实际上修改了字符串,那么您将需要复制它。然而,为了将来的参考,如果您只是处理一个接受 char* 但实际上并未修改参数的旧 c 风格函数,您可以对 c_str() 调用的结果进行 const 转换。
As previous posters have mentioned if the called function does in fact modify the string then you will need to copy it. However for future reference if you are simply dealing with an old c-style function that takes a char* but doesn't actually modfiy the argument, you can const-cast the result of the c_str() call.
如果您需要
std::string
的 C 兼容版本,可以使用c_str();
。请参阅http://www.cppreference.com/wiki/string/basic_string/c_str但它不是
static
,而是const
。如果您的其他函数需要char*
(没有const
),您可以放弃常量(警告!确保该函数不会修改字符串)或创建一个本地按照 codebolt 建议复制。之后不要忘记删除
副本!There is
c_str();
if you need a C compatible version of astd::string
. See http://www.cppreference.com/wiki/string/basic_string/c_strIt's not
static
though butconst
. If your other function requireschar*
(withoutconst
) you can either cast away the constness (WARNING! Make sure the function doesn't modify the string) or create a local copy as codebolt suggested. Don't forget todelete
the copy afterwards!难道您不能将字符串本身传递给采用 char* 的函数吗:
Can't you just pass the string as such to your function that takes a char*: