笔试:使用fprintf和sscanf 判断IP字符串的正确性和数字IP之间的转换

/*****************************************************************
sscanf(const char *buffer,const char *format,[argument ]...)
它的返回值是参数的数据,也就是argument的个数,
buffer:存储的数据,format:格式控制字符串,argument:选择性设定字符串。
******************************************************************/

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
bool isIP(char *str)
{

    int a,b,c,d;
    int ret=0;
    int len=strlen(str);
    str[len]='\0';
    ret=sscanf(str,"%d.%d.%d.%d",&a,&b,&c,&d);
    if(ret==4&&(a>=0&&a<=255)&&(b>=0&&b<=255)&&(c>=0&&c<=255)&&(d>=0&&d<=255))
        return 1;
    else
        return 0;
}
char  *value_to_ip(const long& nValue,char *strTemp)
{
    sprintf( strTemp,"%ld.%ld.%ld.%ld",
                    (nValue&0xff000000)>>24,
                    (nValue&0x00ff0000)>>16,
                    (nValue&0x0000ff00)>>8,
                    (nValue&0x000000ff) );
    return (strTemp);
}
int main(void)
{
    char table[4][15]={"192.168.1.1","0.0.0.0","19999.11.11","199111057239"};
    for(int i=0;i<4;i++)
        cout<<isIP(table[i])<<endl;

    long int num[4]={0,18224001830,2010021050021,610};
    char temp[64]={0};
    for(int i=0;i<4;i++)
        cout<<value_to_ip(num[i],temp)<<endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值