Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Format Specifiers ใน C


Format specifiers ใช้ใน C สำหรับ input และ output เพื่อให้คอมไพเลอร์เข้าใจชนิดข้อมูลในตัวแปรตอนรับ input ด้วย scanf() และพิมพ์ด้วย printf() รายการ format specifiers:

Format Specifierชนิดข้อมูล
%cCharacter
%dSigned integer
%e หรือ %EScientific notation ของ float
%fFloat values
%g หรือ %Gคล้าย %e หรือ %E
%hiSigned integer (short)
%huUnsigned Integer (short)
%iUnsigned integer
%l, %ld, %liLong
%lfDouble
%LfLong double
%luUnsigned int หรือ unsigned long
%lli หรือ %lldLong long
%lluUnsigned long long
%oOctal representation
%pPointer
%sString
%uUnsigned int
%x หรือ %XHexadecimal 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 แบบเดียวกับการพิมพ์