用好printf和scanf

转载自:http://hi.baidu.com/wuxicn/item/f648fe1970f86917e3f98682


在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"



posted @ 2014-03-24 23:49  奋斗中的毛毛虫  Views(289)  Comments(0Edit  收藏  举报