Chinaunix首页 | 论坛 | 博客
  • 博客访问: 632296
  • 博文数量: 135
  • 博客积分: 5217
  • 博客等级: 大校
  • 技术积分: 1289
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-05 17:36
文章分类

全部博文(135)

文章存档

2016年(1)

2012年(5)

2011年(15)

2010年(63)

2009年(51)

分类: C/C++

2009-12-19 21:09:23




在C中,printf系列函数(fprintf, sprintf...)和scanf(fscanf, sscanf...)函数功能很强大,用好了的话,很多字符操作都可以很简单,甚至一些简单的正则匹配的工作也可以用scanf来完成,下面是几个例子。

1. printf:

a) 前导“0”:printf("%05d", n);
// n=10, print: "00010"

b) 左对齐:printf("%-5d|%5d", n, n);
// print: "10   |   10"

c) 自动类型前缀:printf("%#x", n);
// print: "0xa"

d) 指定宽度:printf("%*d", w, n);
// w=5, print: "   10"
                  printf("%*.*lf", 5, 1, f);
// f=123.45, print: "123.5"

e) 取得输出长度: printf("%d%n", n, &len); // print: "10" and len=2, %n must be at the end of the formatting string

2. scanf:

// s="Used with 12,4.5|0x123 specifiers_the\n value.";

a) 基本用法:sscanf(s, "%s %s %d,%f|%x", s1, s2, &a, &f, &b);
// s1="Used"; s2="with"; a=12; f=4.5; b=0x123

b) 跳过一些结果:sscanf(s, "%*s %s", s1);
// %*s reads "Used" and ignores it. s1="with"

c) 限定长度:sscanf(s, "%10s", buf);
// read at most 10 chars into buf.

d) 简单的正则匹配:sscanf(s, "%[a-z]", buf);
// buf="with" not "Used"!
                    sscanf(s, "%3c", buf);
// buf="Use"

e) 读入一整行: sscanf(s, "%[^\n]", buf);
// buf="Used with 12,4.5|0x123 specifiers_the"
阅读(764) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~