C++ examples for Language Basics:Console
Formatting data via printf()
int printf(const char *fmt , arg-list)
Code | Format |
---|---|
%c | Character. |
%d | Signed decimal integers. |
%i | Signed decimal integers. |
%e | Scientific notation (lowercase e). |
%E | Scientific notation (uppercase E). |
%f | Decimal floating point. |
%g | Uses %e or %f, whichever is shorter (if %e, uses lowercase e). |
%G | Uses %E or %f, whichever is shorter (if %E, uses uppercase E). |
%o | Unsigned octal. |
%s | Null-terminated string. |
%u | Unsigned decimal integers. |
%x | Unsigned hexadecimal (lowercase letters). |
%X | Unsigned hexadecimal (uppercase letters). |
%p | Displays an address. |
%n | The associated argument shall be a pointer to an integer, into which is placed the number of characters written so far. |
%% | Prints a % sign. |
The %f format specifier displays a double argument in floating-point format.
The %e and %E specifiers tell printf( ) to display a double argument in scientific notation.
Numbers represented in scientific notation take this general form:
x.dddddE+/-yy
The following program shows several examples of printf().
#include <cstdio> #include <cmath> using namespace std; int main()/*from www .j a v a 2 s . c o m*/ { int x = 10; double val = 568.345; // It is not necessary for a call to printf() to include // format specifiers or additional arguments. printf("This is output to the console.\n"); // Display numeric values. printf("This is x and val: %d %f\n\n", x, val); printf("This is x in uppercase hex: %X\n", x); printf("Mix data %d into %f the format string.\n\n", 19, 234.3); // Specify various precisions, widths, and sign flags. printf("Here is val in various precisions, widths, and sign flags: \n"); printf("|%10.2f|%+12.4f|% 12.3f|%f|\n", val, val, val, val); printf("|%10.2f|%+12.4f|% 12.3f|%f|\n", -val, -val, -val, -val); printf("\n"); // Display column of numbers, right-justified. printf("Right-justify numbers.\n"); for(int i = 1; i < 11; ++i) printf("%2d %8.2f\n", i, sqrt(double(i))); printf("\n"); // Now, left-justify some strings in a 16-character field. // Right-justify the quantities. printf("%-16s Quantity: %3d\n", "Hammers", 12); printf("%-16s Quantity: %3d\n", "Pliers", 6); printf("%-16s Quantity: %3d\n", "Screwdrivers", 19); return 0; }