开发者

Converting a C-style string to a C++ std::string

What is the best way to c开发者_Go百科onvert a C-style string to a C++ std::string? In the past I've done it using stringstreams. Is there a better way?


C++ strings have a constructor that lets you construct a std::string directly from a C-style string:

const char* myStr = "This is a C string!";
std::string myCppString = myStr;

Or, alternatively:

std::string myCppString = "This is a C string!";

As @TrevorHickey notes in the comments, be careful to make sure that the pointer you're initializing the std::string with isn't a null pointer. If it is, the above code leads to undefined behavior. Then again, if you have a null pointer, one could argue that you don't even have a string at all. :-)


Check the different constructors of the string class: documentation You maybe interested in:

//string(char* s)
std::string str(cstring);

And:

//string(char* s, size_t n)
std::string str(cstring, len_str);


C++11: Overload a string literal operator

std::string operator ""_s(const char * str, std::size_t len) {
    return std::string(str, len);
}

auto s1 = "abc\0\0def";     // C style string
auto s2 = "abc\0\0def"_s;   // C++ style std::string

C++14: Use the operator from std::string_literals namespace

using namespace std::string_literals;

auto s3 = "abc\0\0def"s;    // is a std::string


If you mean char* to std::string, you can use the constructor.

char* a;
std::string s(a);

Or if the string s already exist, simply write this:

s=std::string(a);


You can initialise a std::string directly from a c-string:

std::string s = "i am a c string";
std::string t = std::string("i am one too");


In general (without declaring new storage) you can just use the 1-arg constructor to change the c-string into a string rvalue :

string xyz = std::string("this is a test") + 
             std::string(" for the next 60 seconds ") + 
             std::string("of the emergency broadcast system.");

However, this does not work when constructing the string to pass it by reference to a function (a problem I just ran into), e.g.

void ProcessString(std::string& username);
ProcessString(std::string("this is a test"));   // fails

You need to make the reference a const reference:

void ProcessString(const std::string& username);
ProcessString(std::string("this is a test"));   // works.


And yet another way for char arrays now. Similar to std::vector's initialization, at least that's how I remember it.

char cBuf[256] = "Hello World";
std::cout << cBuf << '\n';
std::string str{std::begin(cBuf), std::end(cBuf)};
std::cout << str << '\n';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜