我想将std::string转换为char*或char[]数据类型。
std::string str = "string";
char* chr = str;
结果:"错误:不能转换' std::string '到' char '…"
有什么方法可以做到这一点?
我想将std::string转换为char*或char[]数据类型。
std::string str = "string";
char* chr = str;
结果:"错误:不能转换' std::string '到' char '…"
有什么方法可以做到这一点?
当前回答
没有人提到过sprintf?
std::string s;
char * c;
sprintf(c, "%s", s.c_str());
其他回答
OOP风格的转换
converter.hpp
class StringConverter {
public: static char * strToChar(std::string str);
};
converter.cpp
char * StringConverter::strToChar(std::string str)
{
return (char*)str.c_str();
}
使用
StringConverter::strToChar("converted string")
假设你只需要一个c风格的字符串作为输入传递:
std::string str = "string";
const char* chr = str.c_str();
如果我需要c++字符串内容的可变原始副本,那么我会这样做:
std::string str = "string";
char* chr = strdup(str.c_str());
后来:
free(chr);
So why don't I fiddle with std::vector or new[] like anyone else? Because when I need a mutable C-style raw char* string, then because I want to call C code which changes the string and C code deallocates stuff with free() and allocates with malloc() (strdup uses malloc). So if I pass my raw string to some function X written in C it might have a constraint on it's argument that it has to allocated on the heap (for example if the function might want to call realloc on the parameter). But it is highly unlikely that it would expect an argument allocated with (some user-redefined) new[]!
这个也可以
std::string s;
std::cout<<"Enter the String";
std::getline(std::cin, s);
char *a=new char[s.size()+1];
a[s.size()]=0;
memcpy(a,s.c_str(),s.size());
std::cout<<a;
更多细节在这里,还有这里,但你可以用
string str = "some string" ;
char *cstr = &str[0];
从c++ 11开始,还可以使用str.data()成员函数,该函数返回char *
string str = "some string" ;
char *cstr = str.data();