将std :: string转换为char *替代 [英] Convert std::string to char * alternative

查看:292
本文介绍了将std :: string转换为char *替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在google中做了一个搜索,并被告知这是不可能的,因为我只能从字符串中得到一个静态的 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.

下面是情况:
我有一个.txt文件,其中包含其他.txt文件和一些数字的列表,这样做使程序可以添加到无需重新编译。我使用 ifstream 将文件名读入字符串。

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.

它们需要的函数是期望一个 char * 而不是 string 并且显然这个转换是不可能的。

The function that they are required for is expecting a char * not a string and apparently this conversion is impossible.

我可以访问这个函数,但它调用另一个函数 char * / code>所以我认为im卡住了使用 char *

I have access to this function but it calls another function with the char * so I think im stuck using a char *.

推荐答案

你可以得到一个 const char * 到使用 c_str 的字符串:

You can get a const char* to the string using c_str:

std::string str = "foo bar" ;
const char *ptr = str.c_str() ;

如果你只需要一个char *,你必须复制一份。做:

If you need just a char* you have to make a copy, e.g. doing:

char *cpy = new char[str.size()+1] ;
strcpy(cpy, str.c_str());

这篇关于将std :: string转换为char *替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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