C++ std::string 到 char*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7352099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:49:27  来源:igfitidea点击:

std::string to char*

c++stringchar

提问by Mario

I want to convert a std::stringinto a char*or char[]data type.

我想将std::string转换为char*char[]数据类型。

std::string str = "string";
char* chr = str;

Results in: “error: cannot convert ‘std::string' to ‘char' ...”.

结果是:“错误:无法将 'std::string' 转换为 'char' ...”

What methods are there available to do this?

有哪些方法可以做到这一点?

回答by orlp

It won't automatically convert (thank god). You'll have to use the method c_str()to get the C string version.

它不会自动转换(感谢上帝)。您必须使用该方法c_str()来获取 C 字符串版本。

std::string str = "string";
const char *cstr = str.c_str();

Note that it returns a const char *; you aren't allowed to change the C-style string returned by c_str(). If you want to process it you'll have to copy it first:

请注意,它返回一个const char *; 不允许更改 .c 返回的 C 样式字符串c_str()。如果要处理它,则必须先复制它:

std::string str = "string";
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
// do stuff
delete [] cstr;

Or in modern C++:

或者在现代 C++ 中:

std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1);

回答by bobobobo

More details here, and herebut you can use

更多细节在这里这里,但你可以使用

string str = "some string" ;
char *cstr = &str[0];

回答by Nordic Mainframe

If I'd need a mutable raw copy of a c++'s string contents, then I'd do this:

如果我需要一个 C++ 字符串内容的可变原始副本,那么我会这样做:

std::string str = "string";
char* chr = strdup(str.c_str());

and later:

然后:

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 Cit mighthave 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::vector 或 new[] 呢?因为当我需要一个可变的 C 风格的原始 char* 字符串时,因为我想调用改变字符串的 C 代码,C 代码使用 free() 释放内容并使用 malloc() 分配(strdup 使用 malloc)。因此,如果我将原始字符串传递给某个用 C 编写的函数 X 可能会对其必须在堆上分配的参数进行约束(例如,如果该函数可能想要对参数调用 realloc)。但是它极不可能期望分配有(某些用户重新定义的)new[]!

回答by ildjarn

(This answer applies to C++98 only.)

(此答案仅适用于 C++98。)

Please, don't use a raw char*.

请不要使用原始char*.

std::string str = "string";
std::vector<char> chars(str.c_str(), str.c_str() + str.size() + 1u);
// use &chars[0] as a char*

回答by Lightness Races in Orbit

  • If you just want a C-style string representing the same content:

    char const* ca = str.c_str();
    
  • If you want a C-style string with newcontents, one way (given that you don't know the string size at compile-time) is dynamic allocation:

    char* ca = new char[str.size()+1];
    std::copy(str.begin(), str.end(), ca);
    ca[str.size()] = '
    size_t const MAX = 80; // maximum number of chars
    char ca[MAX] = {};
    std::copy(str.begin(), (str.size() >= MAX ? str.begin() + MAX : str.end()), ca);
    
    ';

    Don't forget to delete[]it later.

  • If you want a statically-allocated, limited-length array instead:

    char const* ca = str.c_str();
    
  • 如果您只想要一个表示相同内容的 C 样式字符串:

    char* ca = new char[str.size()+1];
    std::copy(str.begin(), str.end(), ca);
    ca[str.size()] = '
    size_t const MAX = 80; // maximum number of chars
    char ca[MAX] = {};
    std::copy(str.begin(), (str.size() >= MAX ? str.begin() + MAX : str.end()), ca);
    
    ';
  • 如果您想要一个带有内容的 C 样式字符串,一种方法(假设您在编译时不知道字符串大小)是动态分配:

    vector<char> v(str.begin(), str.end());
    char* ca = &v[0]; // pointer to start of vector
    

    delete[]以后别忘了。

  • 如果你想要一个静态分配的、长度有限的数组:

    std::string str = "string";
    char* chr = const_cast<char*>(str.c_str());
    

std::stringdoesn't implicitly convert to these types for the simple reason that needing to do this is usually a design smell. Make sure that you reallyneed it.

std::string不会隐式转换为这些类型,原因很简单,需要这样做通常是一种设计味道。确保你真的需要它。

If you definitelyneed a char*, the bestway is probably:

如果您确实需要一个char*最好的方法可能是:

std::string str = "string";
const char* chr = str.c_str();

回答by hairlessbear

This would be better as a comment on bobobobo's answer, but I don't have the rep for that. It accomplishes the same thing but with better practices.

作为对 bobobobo 的回答的评论会更好,但我没有代表。它完成了同样的事情,但有更好的做法。

Although the other answers are useful, if you ever need to convert std::stringto char*explicitly without const, const_castis your friend.

尽管其他答案很有用,但如果您需要在没有 const 的情况下显式转换std::stringchar*,那const_cast是您的朋友。

std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];

str.copy(chrs, MAX);

Note that this will notgive you a copy of the data; it will give you a pointer to the string. Thus, if you modify an element of chr, you'll modify str.

请注意,这不会为您提供数据副本;它会给你一个指向字符串的指针。因此,如果您修改 的元素chr,您将修改str

回答by Mark B

Assuming you just need a C-style string to pass as input:

假设您只需要一个 C 样式的字符串作为输入传递:

std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];

memset(chrs, '
char* string_as_array(string* str)
{
    return str->empty() ? NULL : &*str->begin();
}

// test codes
std::string mystr("you are here");
char* pstr = string_as_array(&mystr);
cout << pstr << endl; // you are here
', MAX); str.copy(chrs, MAX-1);

回答by Rob K

To be strictly pedantic, you cannot "convert a std::string into a char* or char[] data type."

严格来说,您不能“将 std::string 转换为 char* 或 char[] 数据类型”。

As the other answers have shown, you can copy the content of the std::string to a char array, or make a const char* to the content of the std::string so that you can access it in a "C style".

正如其他答案所示,您可以将 std::string 的内容复制到 char 数组,或者将 const char* 设置为 std::string 的内容,以便您可以以“C 风格”访问它.

If you're trying to change the content of the std::string, the std::string type has all of the methods to do anything you could possibly need to do to it.

如果您尝试更改 std::string 的内容,则 std::string 类型具有执行您可能需要对其执行的任何操作的所有方法。

If you're trying to pass it to some function which takes a char*, there's std::string::c_str().

如果您试图将它传递给某个需要 char* 的函数,则可以使用 std::string::c_str()。

回答by Jeffery Thomas

For completeness' sake, don't forget std::string::copy().

为了完整起见,不要忘记std::string::copy().

##代码##

std::string::copy()doesn't NUL terminate. If you need to ensure a NUL terminator for use in C string functions:

std::string::copy()不 NUL 终止。如果您需要确保在 C 字符串函数中使用 NUL 终止符:

##代码##

回答by zangw

Here is one more robust version from Protocol Buffer

这是一个更强大的版本 Protocol Buffer

##代码##