Converting a C-style string to a C++ std::string
Asked Answered
S

7

57

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?

Supertanker answered 21/1, 2011 at 23:23 Comment(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?Paraphernalia
F
70

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

Foetid answered 21/1, 2011 at 23:25 Comment(9)
and now I also have to do delete myStr; no?Kravits
@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.Foetid
I see, so I'm guessing right, string makes an internal copy of this char *.Kravits
@BarnabasSzabolcs Yes, though that's independent of whether you need to deallocate the original string.Foetid
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.Umbra
@TrevorHickey While that's true, one could argue that NULL isn't a string. It's the absence of a string.Foetid
@Foetid 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.Umbra
@Foetid 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.Windshield
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.Chan
J
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);
Jana answered 21/1, 2011 at 23:28 Comment(0)
E
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
Ebarta answered 8/7, 2015 at 12:24 Comment(0)
R
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");
Ruffian answered 21/1, 2011 at 23:25 Comment(0)
A
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);
Annatto answered 11/7, 2013 at 1:40 Comment(1)
No. Your example would throw a logic error in std::string's constructor. 'a' cannot be NULL.Umbra
K
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.
Kipkipling answered 9/5, 2014 at 20:51 Comment(0)
R
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';
Roentgenotherapy answered 16/9, 2021 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.