LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 750|回复: 2

[紧急求助]奇怪的输入格式!!

[复制链接]
发表于 2005-8-6 16:58:28 | 显示全部楼层 |阅读模式
小弟遇到一个很奇怪的输入格式问题,麻烦大家解答一下。代码如下:

  1. [color=Red]#define OCTETRANGE "%3d%*1[-]%3d"
  2. #define OCTET "%3d"
  3. #define DOT "%*1[.]"
  4. #define COMP "%7[0-9-]"  
  5. #define REMINDER "%s"[/color]
  6. static int
  7. range(data, s, e)
  8. char * data;
  9. int * s;
  10. int * e;
  11. {
  12. int convs;
  13. int first, last;

  14. [color=Red]convs=sscanf(data, OCTETRANGE, &first, &last);[/color]
  15. if (convs != 2)
  16. {
  17.   /* it didn't work out, so we try converting it as
  18.      an OCTET (xxx) */
  19. [color=Red] convs=sscanf(data, OCTET, &first);[/color]
  20.   if (convs != 1)
  21.   {
  22.    /* that didn't work out either, so it's not a range */
  23.    return (-1);
  24.   }
  25.   else
  26.   {
  27.    /* we'll use these as loop ranges later */
  28.    last = first;
  29.   }
  30. }

  31. if((first < 0) || (first > 255) ||
  32.     (last < 0 ) || (last  > 255))
  33.             return (-1);
  34.        


  35. if(first > last)
  36. {
  37.   /* swap the two vars */
  38. [color=Red] first ^= last;
  39.   last  ^= first;
  40.   first ^= last;[/color]
  41. }

  42. if(s)*s = first;
  43. if(e)*e = last;
  44. return 0;
复制代码

此段程序应该是判断ip方面的功能。红色字体都是小弟不明白的地方。麻烦大家指点一下。下面的程序是我写的测试程序.不知道为什么每次sscanf s[] 后,s就打印不出来。

  1. #include<stdio.h>
  2. #define OCTETRANGE "%3d%*1[-]%3d"
  3. #define OCTET "%3d"
  4. #define DOT "%*1[.]"
  5. #define COMP "%7[0-9-]"  
  6. #define REMINDER "%s"

  7. main()
  8. {
  9.     char s[20]="2399defg[-] 2456";
  10.         int a=1,b=1,c=3;
  11.         c=sscanf(s, OCTETRANGE, &a, &b);
  12.         printf("s=%s\n c=%4d a=%4d b=%4d\n",s,c,a,b);
  13.         //s[20]="abcdefg";
  14.         c=sscanf(s, COMP, &a, &b);
  15.         printf("s=%s\n c=%4d a=%4d b=%4d\n",s,c,a,b);
  16.         c=sscanf(s, OCTET, &a, &b);
  17.         printf("s=%s\n c=%4d a=%4d b=%4d\n",s,c,a,b);
  18.     printf(OCTETRANGE,5,6789,7);
  19.     printf("\n****************************\n");
  20.     printf(COMP,4444);
  21.     printf("\n****************************\n");
  22.     printf(OCTET,4);
  23.     printf("\n****************************\n");
  24.     printf(DOT,456);
  25.     printf("\n");
  26. }
复制代码
发表于 2005-8-6 18:22:41 | 显示全部楼层
man 3 scanf说的非常清楚阿:

%3d -- at most 3 character for decimal integer
%* -- ignore the next token
l[-] any character in [], i.e -

that is equvienlent to:
get at most 3 char for decimal integer, skip one -, then get at most 3 digit

so for the input as :
234-89, a = 234, b = 89
23-8900, a = 23, b = 890
... ...
回复 支持 反对

使用道具 举报

 楼主| 发表于 2005-8-6 20:26:57 | 显示全部楼层
谢谢楼上的兄弟了。惭愧,我没有看scanf函数的man帮助。只是查了一下一个中文的c函数的帮助。没有找到这些。以后以后要养成先看man帮助的习惯了。
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表