a.b.c.d的形式
所以 最简单的方法 就是把ip地址存成字符串str
然后
int a,b,c,d
a=b=c=d=-1
sscanf(str,"%d.%d.%d.%d", &a,&b,&c,&d)
#define chk(x) (x<0 || x>255)
if(chk(a) || chk(b)||chk(c)||chk(d)) printf("failed")
else
{
printf("ok")
}
#include <stdio.h>int isVaildIp(char *ip) {
int dots = 0/*字符.的个数*/
int setions = 0/*ip每一部分总和(0-255)*/
if (NULL == ip || *ip == '.') { /*排除输入参数为NULL, 或者一个字符为'.'的字符串*/
return 0
}
char *p = ip
while (*p) {
if (*p == '.') {
dots ++
if (setions >= 0 &&setions <= 255) { /*检查ip是否合法*/
setions = 0
p++
continue
}
return 0
}
else if (*p >= '0' &&*p <= '9') {
if (p != ip &&*(p - 1) == '0' &&*(p - 2) == '.')
return 0/*判断是不是数字*/
setions = setions * 10 + (*p - '0')/*求每一段总和*/
}
else
return 0
p++
}
if (setions >= 0 &&setions <= 255) {
if (dots == 3) {
return 1
}
}
return 0
}
int main(void) {
int n
scanf("%d", &n)
getchar()
while (n--) {
char s[100]
scanf("%s", s)
if (isVaildIp(s))
puts("YES")
else
puts("NO")
}
return 0
}
根据ip地址的规则 mm.nn.xx.yy,分别取出mm,nn,xx,yy,先判断是否都是数字,再转化为整形数,判断他们的值得范围,就可以确定ip地址是否合法了。朋友,请【采纳答案】,您的采纳是我答题的动力,如果没有明白,请追问。谢谢。