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

cin, cout, cerr, clog Streams ใน C++


ภาพรวม

cin, cout, cerr, clog เป็น stream objects ใน <iostream> จัดการ standard input/output

รายละเอียดแต่ละ Stream

std::cin (Standard Input)

  • Class istream, narrow characters (char)
  • Corresponds to C stdin
  • แหล่งข้อมูล: keyboard, file, environment
  • ใช้ extraction operator >> หรือ member functions (read)

std::cout (Standard Output)

  • Class ostream, narrow characters
  • Corresponds to C stdout
  • Destination: console, file, environment
  • ใช้ insertion operator << หรือ write

std::cerr (Standard Error - Unbuffered)

  • Class ostream
  • Corresponds to C stderr
  • Un-buffered: แสดง error ทันที

std::clog (Standard Error - Buffered)

  • Class ostream
  • Corresponds to C stderr
  • Buffered: เก็บใน buffer จนกว่าจะ flush

คุณสมบัติพิเศษ

Objects เหล่านี้สร้างก่อน static objects ทุกตัวใน translation unit ที่ include <iostream> และ destroy หลัง destructors ของ static objects ทั้งหมด (แต่ flush ระหว่าง program termination) ใช้ได้ปลอดภัยก่อน/หลัง main

ตัวอย่างการใช้งาน

#include <iostream>

int main() {
    int my_int;
    std::cin >> my_int;           // input
    std::cout << my_int;          // normal output
    std::cerr << "An error message"; // error (unbuffered)
    return 0;
}

Compile & Run

$ g++ hello.cpp
$ ./a.out

ผลลัพธ์ (input: 15)

15 An error message