55

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?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Ian Burris
  • 6,325
  • 21
  • 59
  • 80
  • What's a cstring? Do you mean a `CString` from MFC? Or a null-terminated array of char (a C string)? Or something else? – Rob Kennedy Jan 21 '11 at 23:43

7 Answers7

69

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

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • and now I also have to do `delete myStr;` no? – Barney Szabolcs Nov 06 '15 at 14:23
  • 1
    @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. – templatetypedef Nov 06 '15 at 16:07
  • I see, so I'm guessing right, string makes an internal copy of this char *. – Barney Szabolcs Nov 06 '15 at 16:13
  • @BarnabasSzabolcs Yes, though that's independent of whether you need to deallocate the original string. – templatetypedef Nov 06 '15 at 16:43
  • 12
    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. – Trevor Hickey Nov 11 '15 at 13:02
  • 2
    @TrevorHickey While that's true, one could argue that NULL isn't a string. It's the absence of a string. – templatetypedef Nov 11 '15 at 16:30
  • 2
    @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. – Trevor Hickey Nov 11 '15 at 17:02
  • @templatetypedef Yep, it was precisely a std::string s(getenv(foo)) throwing when the env didn't exist that led me here. It's sort of clunky that you can't initialize a string to a null value and have the string remain empty. – Bogatyr Oct 14 '16 at 15:31
  • a variable that is NULL or nullptr still has a type in statically-typed languages, so I do not think it is correct for std::string to throw or go into undefined behavior when given null. It should ideally initialise empty string. – Vallerious Apr 23 '22 at 22:06
14

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);
Santiago Alessandri
  • 6,630
  • 30
  • 46
6

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
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
5

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);
Manas
  • 598
  • 3
  • 14
4

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");
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
2

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.
0

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';
KeyC0de
  • 4,728
  • 8
  • 44
  • 68