C++中char*,string,int类型的相互转换

本文介绍了C++中不同类型之间的转换方法,包括char*到string、string到char*、int到string以及string到int的转换。文章通过具体示例展示了如何使用标准库函数实现这些转换。

1.char*到string类型的转换

可以通过直接将一个char*类型的变量赋值给一个string类型的变量

#include<iostream>
#include<string>
using namespace std;
int main(){
	char *s = "test for conversion";
	string temp;
	temp = s;
	cout << temp << endl;
}

注意上面如果不加#include<string>,则无法直接用cout输出string类型。


2.string到char*类型的转换
string提供了一个方法直接返回字符串的首地址,即string.c_str()方法
#include<iostream>
using namespace std;
int main(){
	char* temp;
	string s = "test for conversion";
	temp = (char*)s.c_str();
	cout << temp << endl;
}

注意这里因为c_str()方法的返回值是const char*类型的,所以前面需要加一个char*进行强制类型转换,或者直接将temp定义为const char*类型,则不需要强制类型转换。


3.int到string类型的转换

int型变量可以直接通过to_string()方法转化为string类型

#include<iostream>
#include<string>
using namespace std;
int main(){
	int a = 10;
	string temp;
	temp = to_string(a);
	cout << temp << endl;
}

4. string到int类型的转换
可以通过stoi()方法将string转换成int类型

#include<iostream>
#include<string>
using namespace std;
int main(){
	int a;
	string temp="10";
	a=stoi(temp);
	cout << a << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值