sprintf函数与sscanf函数的使用小白书77页6174问题

本文详细介绍了C语言和C++中的字符串操作函数sprintf和sscanf的功能和用法,包括数字转字符串、字符串连接、字符提取等功能,并通过实例演示了如何使用这些函数进行字符串的格式化和解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值