derek5. 2008-12-07 19:30 采纳率: 100%
浏览 520
已采纳

如何将 std: : string 转换为 const char * 或 char * ?

How can I convert an std::string to a char* or a const char*?

转载于:https://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char

  • 写回答

8条回答 默认 最新

  • 7*4 2016-01-23 18:13
    关注

    If you just want to pass a std::string to a function that needs const char* you can use

    std::string str;
    const char * c = str.c_str();
    

    If you want to get a writable copy, like char *, you can do that with this:

    std::string str;
    char * writable = new char[str.size() + 1];
    std::copy(str.begin(), str.end(), writable);
    writable[str.size()] = '\0'; // don't forget the terminating 0
    
    // don't forget to free the string after finished using it
    delete[] writable;
    

    Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.

    boost::scoped_array

    boost::scoped_array will delete the memory for you upon going out of scope:

    std::string str;
    boost::scoped_array<char> writable(new char[str.size() + 1]);
    std::copy(str.begin(), str.end(), writable.get());
    writable[str.size()] = '\0'; // don't forget the terminating 0
    
    // get the char* using writable.get()
    
    // memory is automatically freed if the smart pointer goes 
    // out of scope
    

    std::vector

    This is the standard way (does not require any external library). You use std::vector, which completely manages the memory for you.

    std::string str;
    std::vector<char> writable(str.begin(), str.end());
    writable.push_back('\0');
    
    // get the char* using &writable[0] or &*writable.begin()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式