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

ความแตกต่างระหว่าง printf() และ cout ใน C++

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 Valueintvoid (stream)
Performanceเร็วกว่าเล็กน้อยช้ากว่าเล็กน้อย (Sync with stdio)
Extensibilityยาก (Custom Types)ง่าย (Operator<< Overload)

แนะนำ: ใน C++ ใช้ cout เพื่อ Type Safety และ Extensibility