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;
}