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

อ่านไฟล์ ASCII ทั้งไฟล์เข้า std::string ใน C++


วิธีง่ายๆ อ่านไฟล์ ASCII ทั้งไฟล์เข้า std::string ใน C++

อัลกอริทึม

Begin
    เปิดไฟล์ a.txt ด้วย ifstream f
    ประกาศ string str
    If (f เปิดสำเร็จ)
        ประกาศ ostringstream ss
        เรียก f.rdbuf() อ่านข้อมูลทั้งไฟล์
        ใส่ข้อมูลลง ss
        ดึง string จาก ss ใส่ str
    พิมพ์ str
End

โค้ดตัวอย่าง

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main() {
    ifstream f("a.txt");
    string str;
    if (f) {
        ostringstream ss;
        ss << f.rdbuf();  // อ่านข้อมูลทั้งไฟล์
        str = ss.str();
    }
    cout << str;
}

Input

ไฟล์ a.txt มีข้อความ "hi"

Output

hi

ใช้ ostringstream และ rdbuf() เพื่ออ่าน buffer ทั้งหมดของไฟล์ครั้งเดียว