`
java-mans
  • 浏览: 11430814 次
文章分类
社区版块
存档分类
最新评论

判断字符串是否为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;
}





  1. #include<stdio.h>
  2. #include<string.h>
  3. intmain(void)
  4. {
  5. charstr[31],temp[31];
  6. inta,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. return0;
  27. }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics