sprintf函数
sprintf函数原型为 int sprintf(char *str, const char *format, ...)。作用是格式化字符串,具体功能如下所示:
(1)将数字变量转换为字符串。
(2)得到整型变量的16进制和8进制字符串。
(3)连接多个字符串。
举例如下所示:
1 char str[256] = { 0 };
2 int data = 1024;
3 //将data转换为字符串
4 sprintf(str,"%d",data);
5 //获取data的十六进制
6 sprintf(str,"0x%X",data);
7 //获取data的八进制
8 sprintf(str,"0%o",data);
9 const char *s1 = "Hello";
10 const char *s2 = "World";
11 //连接字符串s1和s2
12 sprintf(str,"%s %s",s1,s2);
3、sscanf函数
sscanf函数原型为int sscanf(const char *str, const char *format, ...)。将参数str的字符串根据参数format字符串来转换并格式化数据,转换后的结果存于对应的参数内。具体功能如下:
(1)根据格式从字符串中提取数据。如从字符串中取出整数、浮点数和字符串等。
(2)取指定长度的字符串
(3)取到指定字符为止的字符串
(4)取仅包含指定字符集的字符串
(5)取到指定字符集为止的字符串
sscanf可以支持格式字符%[]:
(1)-: 表示范围,如:%[1-9]表示只读取1-9这几个数字 %[a-z]表示只读取a-z小写字母,类似地 %[A-Z]只读取大写字母
(2)^: 表示不取,如:%[^1]表示读取除'1'以外的所有字符 %[^/]表示除/以外的所有字符
(3),: 范围可以用","相连接 如%[1-9,a-z]表示同时取1-9数字和a-z小写字母
(4)原则:从第一个在指定范围内的数字开始读取,到第一个不在范围内的数字结束%s 可以看成%[] 的一个特例 %[^ ](注意^后面有一个空格!)
解析网址的例子如下所示:
1 const char *s = "http://www.baidu.com:1234";
2 char protocol[32] = { 0 };
3 char host[128] = { 0 };
4 char port[8] = { 0 };
5 sscanf(s,"%[^:]://%[^:]:%[1-9]",protocol,host,port);
6
7 printf("protocol: %s\n",protocol);
8 printf("host: %s\n",host);
9 printf("port: %s\n",port);
10
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cctype>
#include<cassert>
#include<cmath>
#include<algorithm>
#include<cctype>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<cstdlib>
using namespace std;
int a[1005];
int cmp(char a,char b)
{
return a>b;
}
int get_next(int x)
{
int a,b,n;
char s[10];
sprintf(s,"%d",x);
n=strlen(s);
sort(s,s+n);
sscanf(s,"%d",&a);
sort(s,s+n,cmp);
sscanf(s,"%d",&b);
return b-a;
}
int main()
{
int num[1005];
cin>>num[0];
cout<<num[0];
int count=1;
for(;;)
{
num[count]=get_next(num[count-1]);
cout<<" -> "<<num[count];
int found=0;
for(int i=0;i<count;i++)
if(num[count]==num[i])
{
found=1;
break;
}
if(found)
break;
count++;
}
cout<<endl;
return 0;
}