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条)

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊