std::string to C string

std::string to C string

  • 使用 std::basic_string::c_str 方法將字串轉換為 char 陣列
  • 使用 std::vector 容器將字串轉換為 Char 陣列
  • 使用指標操作操作將字串轉換為字元陣列

c_str()

  • return const char*
    1
    2
    string tmp_string = "This will be converted to char*";
    auto c_string = tmp_string.c_str();

string.data()

  • A pointer to the c-string representation of the string object’s value.
  • The pointer returned may be invalidated by further calls to other member functions that modify the object.
  • Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.
    • This array includes the same sequence of characters that make up the value of the string object plus an additional terminating null-character (‘\0’) at the end.
      1
      2
      string str = "some string" ;
      char *cstr = str.data();

由 const char* 轉成 char*

  1. 直接修改函式參數的型態定義,但原本函式庫裡的宣告根本不能改。
  2. 用 const_cast<char*>(cptr),這個雖然可以強制轉換,但若透過轉換後的指標更改常數的值,將會是 undefined behavior。
  3. 使用上一篇提到的 strcpy(),但小心緩衝區覆蓋,或是使用到不知道指到什麼的指標。
  4. Declare C a const, i.e. const char *C = …
    • const char *C = R.c_str();
  5. Copy the content into space that you have allocated.
    1
    2
    3
    4
    5
    char *C = new char[R.size()+1];
    std::strcpy(C, R.c_str());
    // The second problem is a memory leak: your code assigns C a result of new, but never deletes it. If you use strcpy approach, you need to add

    delete[] C;

strncpy

  • cstring