ฟังก์ชัน puts() และ printf() ประกาศใน stdio.h ใช้ส่งข้อความไปยังเอาต์พุตสตรีม แต่มีการใช้งานและไวยากรณ์ต่างกัน
puts()
พิมพ์สตริงพร้อมเพิ่มตัวขึ้นบรรทัดใหม่ (\n) อัตโนมัติ ง่ายกว่าและรวดเร็วกว่า printf()
รูปแบบไวยากรณ์
puts("string");หากไม่ต้องการขึ้นบรรทัดใหม่ ใช้ fputs(string, stdout)
ตัวอย่าง
#include <stdio.h>
int main() {
puts("This is a demo.");
fputs("No new Line.", stdout);
puts(" Welcome!");
getchar();
return 0;
}ผลลัพธ์
This is a demo. No new Line. Welcome!
printf()
พิมพ์ข้อความพร้อมค่าตัวแปร การทำงานซับซ้อนกว่า จึงช้ากว่า puts()
รูปแบบไวยากรณ์
printf("string");ตัวอย่าง
#include <stdio.h>
int main() {
int a = 10;
printf("Hello world! \n");
printf("The value of a : %d", a);
getchar();
return 0;
}ผลลัพธ์
Hello world! The value of a : 10