[Courses] [C] format specifiers (was: yet one more question =))
Katie Bechtold
katie at katie-and-rob.org
Sat Nov 9 18:36:58 EST 2002
On Sat, Nov 09, 2002 at 12:00:39AM -0500, Morgon Kanter wrote:
> What is up with this formatting? :
> printf("%6d", blah);
> - or -
> printf("%6.2d", blah);
The wonderful world of format specifiers! If you specify an integer
right after the percent sign, that is the minimum field width. For
example, while
printf("%d\n", 82);
produces:
82
printf("%6d\n", 82);
produces:
82
If you lead the integer after the percent sign with a 0, it pads the
left side of the output with 0's.
If you specify an integer after a decimal point after the percent
sign, as in %.2f, that's the number of digits after the decimal
point that are displayed. This has no effect on integers; looks
like it's only useful for floating point numbers, which are normally
displayed with a certain number of digits following the decimal
point.
Here's an experimental program:
int main(int argc, char *argv[]) {
int a = 82;
float b = 1.23;
printf("%d\n", a);
printf("%6d\n", a);
printf("%06d\n", a);
printf("%6.2d\n", a);
printf("%f\n", b);
printf("%6f\n", b);
printf("%06f\n", b);
printf("%.2f\n", b);
printf("%3f\n", b);
return 0;
}
And here's its output:
82
82
000082
82
1.230000
1.230000
1.230000
1.23
1.230000
> also, weird, you don't need to include stdio for printf to work.
I think that's weird too. When I look at printf's man page and see
#include <stdio.h> included in the SYNOPSIS, I kind of assume that's
where printf's defined and that I'd need to include it in my program
that calls printf.
--
Katie Bechtold
http://katie-and-rob.org/
More information about the Courses
mailing list