C++之数据类型转换

1、sprintf(其他类型转字符数组)

支持除字符串之外的其他数据类型转换为字符数组类型

#include<iostream>
using namespace std;
int main()
{
	int a=1324;
	char s[100]="dljf";
	sprintf(s,"%s%d",s,a);
	cout<<s;	
} 

2、stringstream

函数名功能
str初始化和打印流中内容
clear清空流
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
	string str,str1="3432";
	int num1; 
	stringstream sstream;
	sstream<<"dlkadfdkf";//向stringstream中传入数据 
	sstream>>str;
	cout<<str<<endl;
	sstream.clear();//进行一个输出清空 
	sstream<<str1;
	sstream>>num1;
	cout<<num1<<endl;
	return 0; 
}
 

3、库函数(c++11支持)

函数名功能
stoi字符串/字符数组转整型数字
atoi字符数组转字符串
atof字符数组转浮点型
atol字符数组转长整形
strtod字符串转浮点型
strtol字符串转长整型
to_string数字类型转字符串
stoi

stoi字符串或字符数组转整形,共有三个参数,第一个参数字符串,第二个参数转换字符串起始的位置,第三个参数字符串末尾位置

#include<iostream>
using namespace std;
int main()
{
	string str="34324";
	int num=stoi(str);
	cout<<num;
	return 0; 
}
atoi

atoi字符数组转整形

#include<iostream>
using namespace std;
int main()
{
	char str[]="34324";
	int num=atoi(str);
	cout<<num;
	return 0; 
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值