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

思路:输入字符串的时候,把分隔符“.”读取出来,然后判断分隔符旁边的数字是否在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 plain copy
  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. }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值