C Format Specifiers
A format specifier tells printf() and scanf() what kind of value to print or read. It starts with %.
Common format specifiers
| Specifier | Used for | Example value |
|---|---|---|
%d or %i | int | 25 |
%u | unsigned int | 3000000000 |
%ld | long | 123456789 |
%f | float (print) | 3.140000 |
%lf | double (scanf) | 3.14 |
%c | char | 'A' |
%s | string | "Hello" |
%x | hexadecimal | ff |
%o | octal | 17 |
%e | scientific | 1.5e+03 |
%% | percent sign | % |
Example
#include <stdio.h>
int main(void) {
int n = 255;
double pi = 3.14159265;
printf("Decimal: %d\n", n);
printf("Hex: %x\n", n);
printf("Octal: %o\n", n);
printf("Float: %f\n", pi);
printf("Two decimals: %.2f\n", pi);
printf("Char: %c\n", 'A');
printf("String: %s\n", "C language");
printf("Percent: 50%%\n");
return 0;
}
Output:
Output of the above program is
Decimal: 255
Hex: ff
Octal: 377
Float: 3.141593
Two decimals: 3.14
Char: A
String: C language
Percent: 50%
Width and alignment
A number between % and the letter sets the minimum width. A minus sign aligns the value to the left. A zero fills with zeros.
#include <stdio.h>
int main(void) {
printf("[%5d]\n", 42);
printf("[%-5d]\n", 42);
printf("[%05d]\n", 42);
printf("[%8.2f]\n", 3.14159);
return 0;
}
Output:
Output of the above program is
[ 42]
[42 ]
[00042]
[ 3.14]
Note:
printf() uses %f for both float and double, but scanf() needs %f for float and %lf for double.
Next: C Type Casting.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |