判断字符串是否为IP地址,用到sscanf和sprintf

来源:互联网 发布:塔罗牌准不准知乎 编辑:程序博客网 时间:2024/05/16 11:22

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

代码:

// IsIpAddre.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"


#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);    //把格式化的数据写入字符串temp
if(strcmp(temp,str)==0) 
{
printf("YES\n"); 

else
{
printf("NO\n"); 
}
}
else 
{
printf("NO\n");
}
}
return 0; 
}





[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. int main(void)   
  4. {  
  5.     char str[31],temp[31];  
  6.     int a,b,c,d;  
  7.     while(gets(str)!=NULL)  
  8.     {  
  9.         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)  
  10.         {  
  11.             sprintf(temp, "%d.%d.%d.%d",a,b,c,d);    //把格式化的数据写入字符串temp  
  12.             if(strcmp(temp,str)==0)   
  13.             {  
  14.                 printf("YES\n");   
  15.             }   
  16.             else  
  17.             {  
  18.                 printf("NO\n");   
  19.             }  
  20.         }  
  21.         else   
  22.         {  
  23.             printf("NO\n");  
  24.         }  
  25.     }  
  26.     return 0;   
  27. }