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

前端 未结 13 1288
借酒劲吻你
借酒劲吻你 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

    std::string vString;
    vString.resize(256); // allocate some space, up to you
    char* vStringPtr(&vString.front());
    // assign the value to the string (by using a function that copies the value).
    // don't exceed vString.size() here!
    // now make sure you erase the extra capacity after the first encountered \0.
    vString.erase(std::find(vString.begin(), vString.end(), 0), vString.end());
    // and here you have the C++ string with the proper value and bounds.
    

    This is how you turn a C++ string to a C string. But make sure you know what you're doing, as it's really easy to step out of bounds using raw string functions. There are moments when this is necessary.

提交回复
热议问题