西工大机试-判断IP地址是否合法

判断IP地址是否合法,有n组测试数,以字符串形式输入,格式为a.b.c.d,每个均为整数,输出判断是否为有效IP,每个数均在[0,255]之间。合法输出Yes,不合法输出No。

输入样例:
2
1.2.3.4
172.168.0.300
输出:
yes
no

#include<iostream>
#include<cstdio>
#include<math.h>
#include<cstring>

using namespace std;

int main()
{
    char s[100];
    int i=0,n;
    cin>>n;
    while(i<n)
    {
        cin>>s;
        int a[4]={0}, j = 0, t = 0, num = 0, l=strlen(s)-1;
        int flag = 1, res = 1;
        int reg = l;

        while(l>=0)
        {
            if(s[l]!='.')
            {
                if(j>3)//if the array crossed the border
                {
                    flag = 0;
                    break;
                }
                else
                    a[j]+=(s[l]-'0')*pow(10,num);//dealing the string in reversed order
                    num++;
            }
            if(s[l]=='.')
            {
                if(l == 0||l == reg)//if the point appeared at the edge of the string
                {
                    flag = 0;
                    break;
                }
                else if(s[l-1] == '.'||s[l+1] == '.')//if the subsequent point existed
                {
                    flag = 0;
                    break;
                }
                else
                {
                    j++;
                    num=0;
                }
            }//if;
            l--;
        }//inside while;the end of dealing the string.

        if(j!=3)//if the number of point was wrong
        {
            flag = 0;
        }

        for(t=0; t<4; t++)//if the data was wrong
        {
            if(a[t]>255||a[t]<0)
            {
                res = 0;
            }
        }
        if(flag == 1)
        {
            if(res == 1)
            {
                cout<<"yes"<<endl;
            }
            else
            {
                cout<<"no"<<endl;
            }
        }
        else
        {
            cout<<"no"<<endl;
        }
        i++;
    }//outside while;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值