Format specifiers ใช้ใน C สำหรับ input และ output เพื่อให้คอมไพเลอร์เข้าใจชนิดข้อมูลในตัวแปรตอนรับ input ด้วย scanf() และพิมพ์ด้วย printf() รายการ format specifiers:
| Format Specifier | ชนิดข้อมูล |
|---|---|
| %c | Character |
| %d | Signed integer |
| %e หรือ %E | Scientific notation ของ float |
| %f | Float values |
| %g หรือ %G | คล้าย %e หรือ %E |
| %hi | Signed integer (short) |
| %hu | Unsigned Integer (short) |
| %i | Unsigned integer |
| %l, %ld, %li | Long |
| %lf | Double |
| %Lf | Long double |
| %lu | Unsigned int หรือ unsigned long |
| %lli หรือ %lld | Long long |
| %llu | Unsigned long long |
| %o | Octal representation |
| %p | Pointer |
| %s | String |
| %u | Unsigned int |
| %x หรือ %X | Hexadecimal representation |
| %n | ไม่พิมพ์อะไร |
| %% | พิมพ์ตัวอักษร % |
นี่คือ format specifiers พื้นฐาน สามารถเพิ่มส่วนอื่นๆ ได้:
- เครื่องหมายลบ (-) บอกให้จัดชิดซ้าย
- ตัวเลขหลัง % ระบุ minimum field width ถ้าสตริงสั้นกว่า จะเติม space
- จุด (.) แยก field width และ precision
ตัวอย่าง
#include <stdio.h> main() { char ch = 'B'; printf("%c\n", ch); int x = 45, y = 90; printf("%d\n", x); printf("%i\n", y); float f = 12.67; printf("%f\n", f); printf("%e\n", f); int a = 67; printf("%o\n", a); printf("%x\n", a); char str[] = "Hello World"; printf("%s\n", str); printf("%20s\n", str); printf("%-20s\n", str); printf("%20.5s\n", str); printf("%-20.5s\n", str); }ผลลัพธ์
B 45 90 12.670000 1.267000e+001 103 43 Hello World Hello World Hello World Hello Hello
ใช้ format specifiers นี้กับ scanf() ได้เหมือนกัน เพื่อรับ input แบบเดียวกับการพิมพ์