用好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"



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值