Can I get a non-const C string back from a C++ string?

前端 未结 13 1293
借酒劲吻你
借酒劲吻你 2020-12-01 15:33

Const-correctness in C++ is still giving me headaches. In working with some old C code, I find myself needing to assign turn a C++ string object into a C string and assign i

13条回答
  •  囚心锁ツ
    2020-12-01 16:13

    You can use the copy method:

    len = myStr.copy(cStr, myStr.length());
    cStr[len] = '\0';
    

    Where myStr is your C++ string and cStr a char * with at least myStr.length()+1 size. Also, len is of type size_t and is needed, because copy doesn't null-terminate cStr.

提交回复
热议问题