Introduction
Announcements

Schedule
Labs
Assignments
TA office hours

Tests, exam

Topic videos
Some course notes
Extra problems
Lecture recordings

Discussion board

Grades so far

printf and scanf format codes

Contents:

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 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 expression type promotions are expected -- in an expression, char and short are converted to int, and float is converted to double. 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 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).