栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ 中 char 与 string 之间的相互转换问题

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ 中 char 与 string 之间的相互转换问题

char转string
#include "stdafx.h"
#include
#include
using namespace std;

int main(int argc, char* argv[])
{
	string x;
	const char *y="hello";
	const char z[]="hello world";
	x=y;
	cout< 

输出

hello
5
hello world
11

从结果可以看出char*和char[]可以直接转换为string

string转char
#include "stdafx.h"
#include
#include
using namespace std;

int main(int argc, char* argv[])
{
	string x="hello";
	const char *y;
	

	y=x.data();
	cout< 

输出

hello
hello
hello

从结果可以看出有两种办法可以将string转为char*类型
通过copy和结尾加斜杠0的办法可以将string转换为char[]

char* 转 char数组
#include "stdafx.h"
#include
#include
using namespace std;

int main(int argc, char* argv[])
{

	// 创建一个字符串数组
	char arr[10] = {0};
	// 创建一个指针,并指向静态区存放的一个字符串“ABC”
	char* tmp = "ABC";
 
	// 利用字符串拷贝函数进行拷贝
	strcpy(arr, tmp);
 
	// 例如内存拷贝函数进行拷贝
	memcpy(arr, tmp, sizeof(arr));

	printf("%s",arr);

	return 0;
}


输出:

ABC
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/528923.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号