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 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器
  • ¥20 SQL server表计算问题
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传