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