printf ใช้พิมพ์สตริงทั่วไปโดยไม่มีฟิลด์รอเติม:
printf ("An ordinary string.."); printf ("Testing 1,2,3...");
กรณีง่ายกว่าคือพิมพ์จำนวนเต็มเดี่ยว:
int number = 48; printf ("%d",number);
รวมทั้งสองอย่างได้:
int number = 48; printf ("Some number = %d",number);
ผลลัพธ์: Some number = 48
รายการตัวอักษรการแปลง (conversion characters) สำหรับ printf:
- d - จำนวนเต็มเครื่องหมาย (signed decimal integer)
- u - จำนวนเต็มไม่มีเครื่องหมาย (unsigned decimal integer)
- x - จำนวนเต็มฐานสิบหก (hexadecimal integer)
- o - จำนวนเต็มฐานแปด (octal integer)
- s - สตริง (string)
- c - ตัวอักษรเดี่ยว (single character)
- f - จุดทศนิยมคงที่ (fixed decimal floating point)
- e - สัญลักษณ์วิทยาศาสตร์ (scientific notation floating point)
- g - ใช้ f หรือ e ichever สั้นกว่า
ตัวอย่าง
โปรแกรม C สาธิต การใช้ printf conversion characters และประเภทต่างๆ:
/* printf Conversion Characters and Types */ #include <stdio.h> main (){ int i = -10; unsigned int ui = 10; float x = 3.56; double y = 3.52; char ch = ’z’; char *string_ptr = "any old string"; printf ("signed integer %d\n", i); printf ("unsigned integer %u\n",ui); printf ("This is wrong! %u",i); printf ("See what happens when you get the "); printf ("character wrong!"); printf ("Hexadecimal %x %x\n",i,ui); printf ("Octal %o %o\n",i,ui); printf ("Float and double %f %f\n",x,y); printf (" ditto %e %e\n",x,y); printf (" ditto %g %g\n",x,y); printf ("single character %c\n",ch); printf ("whole string -> %s",string_ptr); }
ผลลัพธ์
signed integer -10 unsigned integer 10 This is wrong! 4294967286See what happens when you get the character wrong!Hexadecimal fffffff6 a Octal 37777777766 12 Float and double 3.560000 3.520000 ditto 3.560000e+000 3.520000e+000 ditto 3.56 3.52 single character z whole string -> any old string