0

I'd like to initialise a string and then modify the resultant char array. I did:

std::string str = "hello world"; const char* cstr = str.c_str(); // Modify contents of cstr 

However, because cstr is const, I cannot modify the elements. If I remove const, I cannot use c_str().

What is the best way to achieve this?

3
  • 3
    Why can't you modify the string itself? Commented Apr 20, 2017 at 19:06
  • 1
    What is the best way to achieve this? Just modify the std::string directly. Commented Apr 20, 2017 at 19:07
  • It is possible to do this with a const_cast, however, it's a very, very bad idea as internal members in the string assume that only they're modifying the buffer, and depending on how you change it you can get unexpected and strange behavior later. (Don't ask me how I know, I'd rather not think about it again,) Commented Apr 20, 2017 at 19:38

2 Answers 2

4

Just modify str using the std::string member functions.

These functions include operator[].

Since C++11 (and assuming a compliant implementation), &str[0] is the pointer that you want.

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

Comments

0

The best and most straight forward way to do this is to just directly modify the std::string using its own operator[]:

str[0] = 'G'; // "Gello world" 

If you truly need to copy the C-string, for whatever reason, then you have to create a new buffer, eg:

char* buffer = new char[str.length() + 1]; strcpy(buffer, str.c_str()); delete[] buffer; 

The obvious flaw here is dynamic allocation. Just stick with modifying the std::string directly, it's what the class is written for, to make your life easier.

1 Comment

@RemyLebeau Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.