P7911 [CSP-J 2021] 网络连接-sscanf与sprintf的应用

[CSP-J 2021] 网络连接 - 洛谷

本题直接模拟的话会十分复杂,C语言标准库中有两个针对于字符串固定格式输入输出的函数,

下图是给字符型数组ad按照固定格式输入的样例,在此之前,我们已经输入了ad数组,sscanf用于检测按照特定格式输入时成功输入的个数

int cnt=sscanf(ad,"%lld.%lld.%lld.%lld:%lld",&a,&b,&c,&d,&e);

1.2.3.4:5 会返回5

1:2:3:4:5 会返回1

下面是把若干数字转化为固定格式字符串的样例

sprintf(add,"%lld.%lld.%lld.%lld:%lld",a,b,c,d,e);

a,b,c,d,e取1,2,3,4,5时会将add数组赋值为1.2.3.4:5

#include <iostream>
# include<cstdio>
# include<map>
# include<string.h>
using namespace std;
typedef  long long int  ll;
map<string,int>m;
int main ()
{


    int t;
    cin>>t;

    int id=0;
    while(t--)
    {
        char op[1000],ad[1000];
        cin>>op>>ad;
        id++;

        ll a=-1,b=-1,c=-1,d=-1,e=-1;

        int cnt=sscanf(ad,"%lld.%lld.%lld.%lld:%lld",&a,&b,&c,&d,&e),flag=0;
        if(cnt!=5)
            flag=1;

            char add[10000];

            sprintf(add,"%lld.%lld.%lld.%lld:%lld",a,b,c,d,e);



          int len1=strlen(ad),len2=strlen(add);

          if(len1!=len2)
            flag=1;
          else
          {
              for(int i=0;i<len1;i++)
              {
                  if(ad[i]!=add[i])
                  {
                      flag=1;
                      break;
                  }
              }
          }


            if(a<0||a>255||b<0||b>255||c<0||c>255||d<0||d>255)
                flag=1;

            if(e>65535||e<0)
                flag=1;

            if(op[0]=='S')
            {

                string t(ad);
                if(flag)
                {
                    cout<<"ERR"<<'\n';
                }
                else if(m[t])
                {
                    cout<<"FAIL"<<'\n';
                }
                else
                {

                    cout<<"OK"<<'\n';
                    m[t]=id;


                }



            }
            else
            {

                string t(ad);
                if(flag)
                {
                    cout<<"ERR"<<'\n';
                }
                else if(m[t]==0)
                {
                    cout<<"FAIL"<<'\n';
                }

               else if(m[t])
                {
                    cout<<m[t]<<'\n';
                }


            }



    }


    return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qinsanma and Code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值