现在的位置: 首页 > 综合 > 正文

判断字符串是否为IP地址

2013年07月01日 ⁄ 综合 ⁄ 共 409字 ⁄ 字号 评论关闭
判断字符串是否为IP地址

思路:输入字符串的时候,把分隔符“.”读取出来,然后判断分隔符旁边的数字是否在0~~255之间,然后判断是否合法。
代码为:
#include<stdio.h>
#include<string.h>

int main(void)
{
  char str[31],temp[31];
  int a,b,c,d;
  while(gets(str)!=NULL)
  {
    if(sscanf(str,"%d.%d.%d.%d",&a,&b,&c,&d))==4 && a>=0 && a<=255&& b>=0 && b<=255&& c>=0 && c<=255&& d>=0 && d<=255)
	{
	  sprintf(temp,"%d.%d.%d.%d",a,b,c,d);
	  if(strcmp(temp,str)==0)
	  {
	    printf("YES\n");
	  }
	  else
	  {
	    printf("NO\n");
	  }
	}
	else
	{
	  printf("NO\n");
	}
  }
  return 0;
}

抱歉!评论已关闭.