59

What is the best way to convert a C-style string to a C++ std::string? In the past I've done it using stringstreams. Is there a better way?

1
  • What's a cstring? Do you mean a CString from MFC? Or a null-terminated array of char (a C string)? Or something else? Commented Jan 21, 2011 at 23:43

7 Answers 7

71

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. :-)

Sign up to request clarification or add additional context in comments.

9 Comments

and now I also have to do delete myStr; no?
@BarnabasSzabolcs No, that's not necessary. You only need to delete memory allocated with new. Pointers to string literals don't need to be deallocated.
Every answer here fails to mention the obvious edge case. If your char* is NULL, std::string will throw. It will not be an empty string as many would suspect. It's unfortunate that all the top posts on stackoverflow don't mention this, and I suspect many people who google for this simple conversion are dealing with the bugs later.
@TrevorHickey While that's true, one could argue that NULL isn't a string. It's the absence of a string.
@templatetypedef Agreed. The answers here aren't wrong, but a disclaimer about NULL would go a long way in terms of helping others. There are many common functions("getenv()" for example), that may or may not return NULL when called with the same inputs. By giving newcomers a simple one-liner without adding a disclaimer is setting them up for failure.
|
15

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);

Comments

7

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

Comments

6

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);

1 Comment

No. Your example would throw a logic error in std::string's constructor. 'a' cannot be NULL.
5

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");

Comments

3

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.

Comments

1

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.