printf()
- มาจาก C ใช้ใน C++ ได้
- Format Function พิมพ์ไป Standard Output
- ต้องใช้ Format Specifier (%d, %s, %f ฯลฯ)
- ส่งคืน int (จำนวนตัวอักษรที่พิมพ์)
- ไม่ Type-safe (Argument Mismatch ไม่ Error)
รูปแบบ
printf("string %d", variable);
ตัวอย่าง
#include <stdio.h>
int main() {
int a = 24;
printf("Welcome! \n");
printf("The value of a : %d", a);
return 0;
}
cout
- Object ของ iostream ใน C++
- พิมพ์ไป Console
- ไม่ต้อง Format Specifier (Operator Overloading)
- ไม่ส่งคืนค่า
- Type-safe (Compile-time Check)
รูปแบบ
cout << "string" << variable << endl;
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
int a = 28;
cout << "The value of a : " << a;
printf("\nThe value of a : %d", a);
return 0;
}
สรุปเปรียบเทียบ
| คุณสมบัติ | printf() | cout |
|---|---|---|
| ภาษา | C (ใช้ใน C++ ได้) | C++ Native |
| Format Specifier | ต้องใช้ | ไม่ต้องใช้ |
| Type Safety | ไม่มี | มี |
| Return Value | int | void (stream) |
| Performance | เร็วกว่าเล็กน้อย | ช้ากว่าเล็กน้อย (Sync with stdio) |
| Extensibility | ยาก (Custom Types) | ง่าย (Operator<< Overload) |
แนะนำ: ใน C++ ใช้ cout เพื่อ Type Safety และ Extensibility