Wednesday, December 23, 2009

printf C++

Here's a quick summary of the available print format specifiers:

%c character
%d decimal (integer) number (base 10)
%e exponential floating-point number
%f floating-point number
%i integer (base 10)
%o octal number (base 8)
%s a string of characters
%u unsigned decimal (integer) number
%x number in hexadecimal (base 16)
%% print a percent sign
\% print a percent sign
%p print the pointer address

Controlling printf integer width
The "%3d" specifier means a minimum width of three spaces, which, by default, will be right-justified. (Note: the alignment is not currently being displayed properly here.)

printf("%3d", 0); 0
printf("%3d", 123456789); 123456789
printf("%3d", -10); -10
printf("%3d", -123456789); -123456789

Left-justifying printf integer output
To left-justify those previous printf examples, just add a minus sign (-) after the % symbol, like this:

printf("%-3d", 0); 0
printf("%-3d", 123456789); 123456789
printf("%-3d", -10); -10
printf("%-3d", -123456789); -123456789

The printf zero-fill option
To zero-fill your integer output, just add a zero (0) after the % symbol, like this:

printf("%03d", 0); 000
printf("%03d", 1); 001
printf("%03d", 123456789); 123456789
printf("%03d", -10); -10
printf("%03d", -123456789); -123456789

printf - integers with formatting
Here is a collection of examples for integer printing. Several different options are shown, including a minimum width specification, left-justified, zero-filled, and also a plus sign for positive numbers.

Description Code Result
At least five wide printf("'%5d'", 10); ' 10'
At least five-wide, left-justified printf("'%-5d'", 10); '10 '
At least five-wide, zero-filled printf("'%05d'", 10); '00010'
At least five-wide, with a plus sign printf("'%+5d'", 10); ' +10'
Five-wide, plus sign, left-justified printf("'%-+5d'", 10); '+10 '

printf - floating point numbers
Here are several examples showing how to print floating-point numbers.

Description Code Result
Print one position after the decimal printf("'%.1f'", 10.3456); '10.3'
Two positions after the decimal printf("'%.2f'", 10.3456); '10.35'

Eight-wide, two positions after the decimal
printf("'%8.2f'", 10.3456); ' 10.35'

Eight-wide, four positions after the decimal
printf("'%8.4f'", 10.3456); ' 10.3456'

Eight-wide, two positions after the decimal, zero-filled
printf("'%08.2f'", 10.3456); '00010.35'

Eight-wide, two positions after the decimal, left-justified
printf("'%-8.2f'", 10.3456); '10.35 '
Printing a much larger number with that same format
printf("'%-8.2f'", 101234567.3456); '101234567.35'

How to print strings with printf formatting
Here are several printf formatting examples that show how to format string output with printf format specifiers.

Description Code Result
A simple string printf("'%s'", "Hello"); 'Hello'
A string with a minimum length printf("'%10s'", "Hello"); ' Hello'
Minimum length, left-justified printf("'%-10s'", "Hello"); 'Hello '

1 comment: