printf and scanf format codes

printf and scanf key letters

The first argument to printf() or scanf() is a format string. In printf(), most things are output directly except for format codes beginning with a '%'. Key letters show data type AND formatting.

The most important key letters are d, g (usually used as "lg"), and s.

codetypeformat
dintdecimal (base ten) number
ointoctal number (no leading '0' supplied in printf)
x or Xinthexadecimal number (no leading '0x' supplied in printf; accepted if present in scanf) (for printf, 'X' makes it use upper case for the digits ABCDEF)
ldlongdecimal number ('l' can also be applied to any of the above to change the type from 'int' to 'long')
uunsigneddecimal number
luunsigned longdecimal number
cchar [footnote]single character
schar pointerstring
ffloat [footnote]number with six digits of precision
gfloat [footnote]number with up to six digits of precision
efloat [footnote]number with up to six digits of precision, scientific notation
lfdouble [footnote]number with six digits of precision
lgdouble [footnote]number with up to six digits of precision
ledouble [footnote]number with up to six digits of precision, scientific notation

Footnote: In printf(), the rvalue type promotions are expected. Thus %c actually corresponds to a parameter of type int and %f and %g actually correspond to parameters of type double. Thus in printf() there is no difference between %f and %lf, or between %g and %lg. However, in scanf() what is passed is a pointer to the variable so no rvalue type promotions occur or are expected. Thus %f and %lf are quite different in scanf, but the same in printf.

Personally, I used to use %lg routinely for doubles in both printf and scanf, but this is out of favour these days and indeed gcc will give you a warning message for using %lg in printf. The usual procedure these days is to use %g for double in printf and %lg for double in scanf. It doesn't matter which you use for printf because the printf library function treats them as synonymous, but it's crucial to get it right for scanf.

 


printf format modifiers

Modifiers appear between the '%' and the key letter.

Example of '0':

int dollars = 2;
int cents = 3; /* $2.03 */
printf(" ?? what goes here ?? ", dollars, cents);
If format isthen output is
"$%d.%d"$2.3
"$%d.%2d"$2. 3    (one space between "." and "3")
"$%d.%02d"$2.03

In "%02d", the 0 is not part of the field width. It is a modifier character. And when you have a field width, you must write it such that it does not start with a zero (and then you can prepend a zero as a modifier character if you want that).

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值