C++语法(二)string和int、long int、float的转换

头文件是

#include<string>

一、string转其他类型

1、string转int

// string转int
string str = "123";
int num = atoi(str.c_str());
cout << num << endl;
// 123

2、string转long int

string str = "1234567890";
long int num = atol(str.c_str());
cout << num << endl;
// 1234567890

3、string转float

string str = "12.326374837251427";
double num = atof(str.c_str());
cout << num << endl;
// 12.3264

二、其他类型转string

如int、long int、float等类型转换为string时,都可用to_string()函数来转换,这里仅以int、float示例。

1、int转string

int num = 123;
string str = to_string(num);
cout << str << endl;
// 123

2、float转string

float num = 12.345432;
string str = to_string(num);
cout << str << endl;
// 12.345432

注意,在dev c++中可能无法执行atoi、atol和atof函数。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值