如何将std::string转换为char*或const char*?
当前回答
对于const char *使用.c_str()方法。
你可以使用&mystring[0]来获得一个char *指针,但是有几个问题:你不一定会得到一个以0结尾的字符串,你也不能改变字符串的大小。特别要注意的是,不要添加超过字符串结尾的字符,否则会导致缓冲区溢出(并可能导致崩溃)。
在c++ 11之前,并不能保证所有字符都是同一个连续缓冲区的一部分,但实际上,所有已知的std::string实现都是这样工作的;参见“&s[0]”是否指向std::string中的连续字符?
请注意,许多字符串成员函数将重新分配内部缓冲区,并使您可能保存的任何指针无效。最好立即使用,然后丢弃。
其他回答
char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
对于const char *使用.c_str()方法。
你可以使用&mystring[0]来获得一个char *指针,但是有几个问题:你不一定会得到一个以0结尾的字符串,你也不能改变字符串的大小。特别要注意的是,不要添加超过字符串结尾的字符,否则会导致缓冲区溢出(并可能导致崩溃)。
在c++ 11之前,并不能保证所有字符都是同一个连续缓冲区的一部分,但实际上,所有已知的std::string实现都是这样工作的;参见“&s[0]”是否指向std::string中的连续字符?
请注意,许多字符串成员函数将重新分配内部缓冲区,并使您可能保存的任何指针无效。最好立即使用,然后丢弃。
试试这个
std::string s(reinterpret_cast<const char *>(Data), Size);
我正在使用一个API,其中有很多函数获得char*作为输入。
我创建了一个小类来处理这类问题,并且实现了RAII习惯用法。
class DeepString
{
DeepString(const DeepString& other);
DeepString& operator=(const DeepString& other);
char* internal_;
public:
explicit DeepString( const string& toCopy):
internal_(new char[toCopy.size()+1])
{
strcpy(internal_,toCopy.c_str());
}
~DeepString() { delete[] internal_; }
char* str() const { return internal_; }
const char* c_str() const { return internal_; }
};
你可以这样使用它:
void aFunctionAPI(char* input);
// other stuff
aFunctionAPI("Foo"); //this call is not safe. if the function modified the
//literal string the program will crash
std::string myFoo("Foo");
aFunctionAPI(myFoo.c_str()); //this is not compiling
aFunctionAPI(const_cast<char*>(myFoo.c_str())); //this is not safe std::string
//implement reference counting and
//it may change the value of other
//strings as well.
DeepString myDeepFoo(myFoo);
aFunctionAPI(myFoo.str()); //this is fine
我将这个类称为DeepString,因为它正在创建一个现有字符串的深度且唯一的副本(DeepString不可复制)。
看看这个:
string str1("stackoverflow");
const char * str2 = str1.c_str();
但是,请注意,这将返回一个const char *。
对于char *,使用strcpy将其复制到另一个char数组中。