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

การเปรียบเทียบ endl และ \n ใน C++


ความแตกต่างหลัก

  • \n: พิมพ์ newline (platform-specific: Windows เป็น \r\n) ไม่ flush stream
  • std::endl: พิมพ์ newline และ flush stream

แนวทางการใช้งาน

ปกติไม่ต้อง flush stream ทันที เพราะส่งผลต่อ performance ควรใช้ \n แทน

ใช้ std::endl เมื่อต้องการ flush ด้วยตนเอง เช่น ต้องการให้ output แสดงให้ผู้ใช้เห็นทันที (logging, progress, interactive prompts)

สรุป

คุณสมบัติ\nstd::endl
Newline✓✓
Flush stream✗✓
Performanceดีกว่าช้ากว่า
ใช้เมื่อไหร่ทั่วไปต้องการ flush ทันที