Lotus@ 2008-12-07 19:30 采纳率: 100%
浏览 2005
已采纳

如何将 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条回答 默认 最新

  • 叼花硬汉 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条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码