| ||
To understand what a format string is, you need to understand the problem that format strings solve. Most programs output textual data in some form, often including numerical data. Say, for example, that a program wanted to output a string containing an amount of money. The actual amount might be held within the program in the form of a double-precision floating-point number, like this:
double AmountInSterling;
Let's say the amount in pounds sterling is 30432.36. We would like to output the amount exactly as writtenpreceded by a pound sign (), with a decimal point and two places after it. In the absence of format strings, we would have to write a fairly substantial amount of code just to format a number in this way, and even then, it would likely work only for the double-data type and the pounds sterling currency. Format strings provide a more generic solution to this problem by allowing a string to be output that includes the values of variables , formatted precisely as dictated by the programmer. To output the number as specified, we would simply call the printf function, which outputs the string to the process's standard output ( stdout ).
printf("%.2f\n", AmountInSterling);
The first parameter to this function is the format string. This specifies a constant string with placeholders that specify where variables are to be substituted into the string. To output a double using a format string, you use the format specifier %f . You can control aspects of how the data is output using the flags, width, and precision components of the format specifierin this case, we are using the precision component to specify that we require two places after the decimal point. We do not make use of the width and precision components in this simple example.
Just so you get the flavor of it, here is another example that outputs an ASCII reference, with the characters specified in decimal, hex, and their ASCII equivalents.
#include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { int c; printf("Decimal Hex Character\n"); printf("======= === =========\n"); for(c = 0x20; c < 256; c++) { switch(c) { case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x1b: printf(" %03d %02x \n", c, c); break; default: printf(" %03d %02x %c\n", c, c, c); break; } } return 1; }
The output looks like this:
Decimal Hex Character ======= === ========= 032 20 033 21 ! 034 22 " 035 23 # 036 24 $ 037 25 % 038 26 & 039 27 ' 040 28 (041 29) 042 2a * 043 2b + 044 2c , 045 2d - 046 2e .
Note that in this example we are displaying the character in three different waysusing three different format specifiersand with different width specifiers to make sure everything lines up nicely .
| ||