C++ string to Cstring

Hello!

I'm wondering how to convert a C++ string to a C string, but without using the the C++ string function c_str().
Uh not sure why you would want to do that manually, but you could always use
operator[] which std::string implements. http://www.cplusplus.com/reference/string/string/operator[]/

Just iterate through, pulling out each character and assigning it to a C-style string.
It's for an assignment, and we were explicitly told not to use the c_str() operator. :) Trust me, I would have definitely used it if I could. XD
What's the difference between a C_String and a normal C++ string. Just that it ends with '\0'?
There is string::copy()
http://www.cplusplus.com/reference/string/string/copy/

Prior to C++11 the data storage of std::string was not guaranteed to be contiguous so you could not (officially[1]) use the operator[] plus address-of trick -- e.g. &example[0] -- you had to use string::c_str() or string::data() to get a char* pointer to a valid C string. Of course, you can use operator or a per-char basis, as ResidentBiscuit suggested. Or an iterator.

You could also use std::copy algorithm to copy from the string into a buffer.

Andy

[1] Some implementations did use contiguous storage.
Last edited on
Topic archived. No new replies allowed.