C++ 将 char* 转换为 std::string

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1195675/
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-27 19:08:13  来源:igfitidea点击:

convert a char* to std::string

c++stdstring

提问by Jonathan Prior

I need to use an std::stringto store data retrieved by fgets(). To do this I need to convert the char*return value from fgets()into an std::stringto store in an array. How can this be done?

我需要使用std::string来存储由fgets(). 为此,我需要将char*返回值从fgets()转换为std::string以存储在数组中。如何才能做到这一点?

回答by Jesse Beder

std::stringhas a constructor for this:

std::string有一个构造函数:

const char *s = "Hello, World!";
std::string str(s);

Note that this construct deep copies the character list at sand sshould not be nullptr, or else behavior is undefined.

请注意,此构造深复制字符列表s并且s不应该是nullptr,否则行为未定义。

回答by Eugene

If you already know size of the char*, use this instead

如果您已经知道 char* 的大小,请改用它

char* data = ...;
int size = ...;
std::string myString(data, size);

This doesn't use strlen.

这不使用 strlen。

EDIT: If string variable already exists, use assign():

编辑:如果字符串变量已经存在,使用assign():

std::string myString;
char* data = ...;
int size = ...;
myString.assign(data, size);

回答by Paul

I need to use std::string to store data retrieved by fgets().

我需要使用 std::string 来存储由 fgets() 检索到的数据。

Why using fgets()when you are programming C++? Why not std::getline()?

为什么fgets()在编写 C++ 时使用?为什么不std::getline()呢?

回答by Atul

Most answers talks about constructingstd::string.

大多数答案都涉及构建std::string.

If already constructed, just use assignment operator.

如果已经构造,只需使用赋值运算符

std::string oString;
char* pStr;

... // Here allocate and get character string (e.g. using fgets as you mentioned)

oString = pStr; // This is it! It copies contents from pStr to oString

回答by James Thompson

Pass it in through the constructor:

通过构造函数传入:

const char* dat = "my string!";
std::string my_string( dat );

You can use the function string.c_str() to go the other way:

您可以使用函数 string.c_str() 来反其道而行之:

std::string my_string("testing!");
const char* dat = my_string.c_str();

回答by James Thompson

const char* charPointer = "Hello, World!\n";
std::string strFromChar;
strFromChar.append(charPointer);
std::cout<<strFromChar<<std::endl;

回答by Presen

char* data;
stringstream myStreamString;
myStreamString << data;
string myString = myStreamString.str();
cout << myString << endl;

回答by Erik van Velzen

I would like to mention a new method which uses the user defined literal s. This isn't new, but it will be more common because it was added in the C++14 Standard Library.

我想提到一种使用用户定义文字的新方法s。这不是新的,但它会更常见,因为它被添加到 C++14 标准库中。

Largely superfluous in the general case:

在一般情况下基本上是多余的:

string mystring = "your string here"s;

But it allows you to use auto, also with wide strings:

但它允许您使用 auto,也可以使用宽字符串:

auto mystring = U"your UTF-32 string here"s;

And here is where it really shines:

这就是它真正闪耀的地方:

string suffix;
cin >> suffix;
string mystring = "mystring"s + suffix;

回答by user1564286

I've just been struggling with MSVC2005 to use the std::string(char*)constructor just like the top-rated answer. As I see this variant listed as #4 on always-trusted http://en.cppreference.com/w/cpp/string/basic_string/basic_string, I figure even an old compiler offers this.

我一直在努力使用 MSVC2005 来使用std::string(char*)构造函数,就像评分最高的答案一样。当我在始终信任的http://en.cppreference.com/w/cpp/string/basic_string/basic_string上看到这个变体被列为#4 时,我认为即使是旧的编译器也提供了这个。

It has taken me so long to realize that this constructor absolute refuses to match with (unsigned char*)as an argument ! I got these incomprehensible error messages about failure to match with std::stringargument type, which was definitely not what I was aiming for. Just casting the argument with std::string((char*)ucharPtr)solved my problem... duh !

我花了很长时间才意识到这个构造函数绝对拒绝将 with(unsigned char*)作为参数匹配!我收到了这些关于无法与std::string参数类型匹配的难以理解的错误消息,这绝对不是我的目标。只是通过std::string((char*)ucharPtr)解决我的问题来解决我的问题......呃!

回答by Vern Jensen

Not sure why no one besides Erik mentioned this, but according to this page, the assignment operator works just fine. No need to use a constructor, .assign(), or .append().

不知道为什么除了 Erik 没有人提到这一点,但根据这个页面,赋值运算符工作得很好。无需使用构造函数、.assign() 或 .append()。

std::string mystring;
mystring = "This is a test!";   // Assign C string to std:string directly
std::cout << mystring << '\n';