convert a char* to std::string

2019-01-09 23:49发布

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

标签: c++ stdstring
11条回答
The star\"
2楼-- · 2019-01-10 00:36

Most answers talks about constructing 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
查看更多
对你真心纯属浪费
3楼-- · 2019-01-10 00:37

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.

Largely superfluous in the general case:

string mystring = "your string here"s;

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

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;
查看更多
地球回转人心会变
4楼-- · 2019-01-10 00:38

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

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

查看更多
Viruses.
5楼-- · 2019-01-10 00:40

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

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

This doesn't use strlen.

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

std::string myString;
char* data = ...;
int size = ...;
myString.assign(data, size);
查看更多
迷人小祖宗
6楼-- · 2019-01-10 00:43

std::string has a constructor for this:

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

Just make sure that your char * isn't NULL, or else the behavior is undefined.

查看更多
登录 后发表回答