sprintf指的是字符串格式化命令
头文件:#include<stdio.h>
功能:把格式化的数据读入某个字符串中(最终结果是字符串类型)
格式:
char str[100];
str( 字符串名,控制格式符,待转化数字 )
注意:控制格式符要用双引号
1.进制转换用法
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
char str[100];
sprintf(str,"%d",1239);
cout<<"转化十进制读入字符串:"<<str<<endl<<endl;
sprintf(str,"%o",1239);
cout<<"转化八进制读入字符串:"<<str<<endl<<endl;
sprintf(str,"%#o",1239);
cout<<"转化规范化八进制读入字符串:"<<str<<endl<<endl;
sprintf(str,"%x",1239);
cout<<"转化十六进制读入字符串:"<<str<<endl<<endl;
sprintf(str,"%#x",1239);
cout<<"转化规范化16进制读入字符串:"<<str<<endl<<endl;
return 0;
}
2.与C++string结合实现数字转换字符操作
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
char str[100];
sprintf(str,"%d",1239);
string s(str);
cout<<s<<endl;
return 0;
}
3.字符串拼接操作
#include<cstdio>
int main(){
char *a="abc";
char *b="def";
char str[10];
sprintf(str,"%s%s",a,b);
printf("%s\n",str);
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)