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

โครงสร้างคลาสสตรีม (Stream Classes) ใน C++

ใน C++ สตรีม (stream) หมายถึงกระแสของตัวอักษรที่ถูกถ่ายโอนระหว่างเธรดของโปรแกรมกับอินพุต/เอาต์พุต

คลาสสตรีม (Stream classes) ใน C++ ใช้สำหรับการดำเนินการป้อนข้อมูลและแสดงผลบนไฟล์และอุปกรณ์ I/O คลาสเหล่านี้มีคุณสมบัติเฉพาะเพื่อจัดการป้อนข้อมูลและแสดงผลของโปรแกรม

ไลบรารี iostream.h จัดเก็บคลาสสตรีมทั้งหมดในภาษา C++

มาดูลำดับชั้นและเรียนรู้เกี่ยวกับคลาสเหล่านี้:

โครงสร้างคลาสสตรีม (Stream Classes) ใน C++

ตอนนี้มารู้จักคลาสต่างๆ ในไลบรารี iostream:

คลาส ios - เป็นคลาสฐานสำหรับคลาสสตรีมทั้งหมด สตรีมอาจเป็นสตรีมป้อนเข้า (input) หรือสตรีมแสดงผล (output) คลาสนี้กำหนดสมาชิกที่เป็นอิสระจากวิธีที่เทมเพลตของคลาสถูกกำหนด

คลาส istream - จัดการสตรีมป้อนเข้าใน C++ ออบเจ็กต์สตรีมป้อนเข้าเหล่านี้ใช้สำหรับอ่านและแปลความหมายของข้อมูลป้อนเข้าเป็นลำดับของตัวอักษร cin จัดการป้อนเข้า

คลาส ostream - จัดการสตรีมแสดงผลใน C++ ออบเจ็กต์สตรีมแสดงผลเหล่านี้ใช้สำหรับเขียนข้อมูลเป็นลำดับของตัวอักษรบนหน้าจอ cout และ puts จัดการสตรีมแสดงผลใน C++

ตัวอย่าง

สตรีมแสดงผล (OUT STREAM)

COUT

#include <iostream>
using namespace std;
int main() {
    cout << "This output is printed on screen";
}

ผลลัพธ์

This output is printed on screen

PUTS

#include <iostream>
using namespace std;
int main() {
    puts("This output is printed using puts");
}

ผลลัพธ์

This output is printed using puts

สตรีมป้อนเข้า (IN STREAM)

CIN

#include <iostream>
using namespace std;
int main() {
    int no;
    cout << "Enter a number ";
    cin >> no;
    cout << "Number entered using cin is " << no;
}

ผลลัพธ์

Enter a number 3453
Number entered using cin is 3453

GETS

#include <iostream>
using namespace std;
int main() {
    char ch[10];
    puts("Enter a character array");
    gets(ch);
    puts("The character array entered using gets is: ");
    puts(ch);
}

ผลลัพธ์

Enter a character array thdgf
The character array entered using gets is: thdgf