How to convert a std::string to const char* or char*?
How to convert a std::string to const char* or char*?
1.
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()
shareimprove this answer
原文地址:http://stackoverflow.com/questions/347949/how-to-convert-a-stdstring-to-const-char-or-char
2.
1
down vote
accepted
You can get a pointer to the string buffer by simply calling std::string.c_str(). That will return a const char* (where char is an int8_t) that you can effectively use as a byte[]. Keep in mind though that the pointer returned is pointing to memory managed by the string object, so if you change anything in the original string class, you will invalidate the pointer. Also since it's a pointer to a const char, you shouldn't change any values in the buffer. So if you need more permanent memory, or need a buffer you can modify, a better way to accomplish your goal would be to-do (using gcc, which shouldn't be a problem since you're on Ubuntu):
std::string my_string;
char string_array[my_string.length() + 1];
strcpy(string_array, my_string.c_str());
Now use the string_array as your memory buffer.
If you need to return the buffer from a function, you're going to have to allocate the buffer on the heap and return a pointer. That also means you're going to have to call delete [] on the pointer as well after you're done with it, or else you're going to end up with a memory leak. So you could do the following:
#include <string>
#include <cstring>
char* return_buffer(const std::string& string)
{
char* return_string = new char[string.length() + 1];
strcpy(return_string, string.c_str());
return return_string;
}
//now use in code
int main()
{
std::string some_string = "Stuff";
char* buffer = return_buffer(some_string);
//...do something with buffer
//...after you're done with the buffer to prevent memory leak
delete [] buffer;
return 0;
}
shareimprove this answer
How to convert a std::string to const char* or char*?的更多相关文章
- std::string stringf(const char* format, ...)
std::string stringf(const char* format, ...){ va_list arg_list; va_start(arg_list, format); // SUSv2 ...
- 类 this指针 const成员函数 std::string isbn() const {return bookNo;}
转载:http://www.cnblogs.com/little-sjq/p/9fed5450f45316cf35f4b1c17f2f6361.html C++ Primer 第07章 类 7.1.2 ...
- 类型安全且自动管理内存的返回 std::string 的 sprintf 实现
在这篇博文里,我提到了一个例子,说的是使用C++实现类型安全的printf.这个例子很惊艳,但是在我写程序的时候,并非那么"迫切"地需要它出现在我的工具箱中,因为它并不比普通的pr ...
- VC++ 中使用 std::string 转换字符串编码
目录 第1章说明 1 1.1 代码 1 1.2 使用 4 第1章说明 VC++中宽窄字符串的相互转换比较麻烦,借助std::string能大大减少代码量. 1.1 代码 函数声明如下 ...
- C++ std::unordered_map使用std::string和char *作key对比
最近在给自己的服务器框架加上统计信息,其中一项就是统计创建的对象数,以及当前还存在的对象数,那么自然以对象名字作key.但写着写着,忽然纠结是用std::string还是const char *作ke ...
- std::string的拷贝赋值研究
说明:以下涉及的std::string的源代码摘自4.8.2版本.结论:std::string的拷贝复制是基于引用计数的浅拷贝,因此它们指向相同的数据地址. // std::string类定义type ...
- 如何使用 window api 转换字符集?(std::string与std::wstring的相互转换)
//宽字符转多字节 std::string W2A(const std::wstring& utf8) { int buffSize = WideCharToMultiByte(CP_ACP, ...
- UTF8与std:string互转
Ajax请求发送的UTF8编码字符串传到后台使用std:string进一步处理,如果包含中文会出现中文乱码的问题: 特找了一下转码的解决方法,直接代码如下: C++ Code 1234567891 ...
- std::string与std::wstring互相转换
作者:zzandyc来源:CSDN原文:https ://blog.csdn.net/zzandyc/article/details/77540056 版权声明:本文为博主原创文章,转载请附上博文链接 ...
随机推荐
- Sitecore 十大优秀功能
为客户的需求创建最佳解决方案是我们的主要目标.良好的设计不仅仅是视觉吸引力,还要确保用户体验简单直观.在设计Sitecore网站时,我们始终牢记这一点 . 以下是一些我最喜欢的功能,可以帮助我们使用 ...
- Spring Boot + Vue 前后端分离开发,权限管理的一点思路
在传统的前后端不分的开发中,权限管理主要通过过滤器或者拦截器来进行(权限管理框架本身也是通过过滤器来实现功能),如果用户不具备某一个角色或者某一个权限,则无法访问某一个页面. 但是在前后端分离中,页面 ...
- 五、Hexo静态博客背景及界面显示优化配置
示例预览:我的主页 背景图片添加 自动切换背景 静态本地背景 首先将已选定的背景图片放到博客根目录下的\source\images下 示例:D:\Blog\source\images\backgr ...
- 【ELK】elasticsearch中使用脚本报错:scripts of type [inline], operation [update] and lang [groovy] are disabled
查看ID为2的这条数据: 使用更新命令: 使用脚本对年龄+5 curl -XPOST http://192.168.6.16:9200/my_new_index/user/2/_update?pret ...
- Python学习笔记之使用 python -m SimpleHTTPServer 快速搭建http服务
0x00 概述 搭建FTP,或者是搭建网络文件系统,这些方法都能够实现Linux的目录共享.但是FTP和网络文件系统的功能都过于强大,因此它们都有一些不够方便的地方.比如你想快速共享Linux系统的某 ...
- [转]ASP.NET Core Web API 最佳实践指南
原文地址: ASP.NET-Core-Web-API-Best-Practices-Guide 转自 介绍# 当我们编写一个项目的时候,我们的主要目标是使它能如期运行,并尽可能地满足所有用户需求. 但 ...
- VS2008激活找不到密匙输入框
VS2008试用版到期后会无法使用,网上一搜就能找到很多激活码: Visual Studio 2008 Professional Edition: XMQ2Y-4T3V6-XJ48Y-D3K2V-6C ...
- SharpSocket类库功能介绍
SharpSocket是高性能.轻量级.接口清晰.使用简单的C#语言编写的.NET通信类库.支持TCP收发文本和二进制数据,比如图片.音视频.文档等各类数据.SharpSocket封装了很多底层通信细 ...
- Golang程序调试工具介绍(gdb vs dlv)
原文:http://lday.me/2017/02/27/0005_gdb-vs-dlv/ 通过log库输出日志,我们可以对程序进行异常分析和问题追踪.但有时候,我也希望能有更直接的程序跟踪及定位工具 ...
- 关于VS C++中项目属性的一些名称的含义
这个属性页(Alt + F7)界面下的$开头的内容的含义 $(Platform), X64或X86类似的. $(SolutionDir),.sln的位置 $(Configuration), Debug ...