Converting String to Cstring in C++

Viewed 135575

I have a string to convert, string = "apple" and want to put that into a C string of this style, char *c, that holds {a, p, p, l, e, '\0'}. Which predefined method should I be using?

4 Answers

You can do it by 2 steps.

  1. convert string -> const char*

  2. const char* -> CString

string st = "my str";
const char* stBuf = st.c_str();   // 1. string to const char *

size_t sz;                          // save converted string's length + 1
wchar_t output[50] = L"";          // return data, result is CString data

mbstowcs_s(&sz, output,  50, stBuf, 50); // converting function

CString cst = output;
Related