โปรแกรม C++ อ่านเนื้อหาไฟล์เข้า istringstream
ตัวอย่างโค้ด
#include <fstream>
#include <sstream>
#include <iostream>
using namespace std;
int main() {
ifstream is("a.txt", ios::binary);
// หาความยาวไฟล์
is.seekg(0, ios::end);
long length = is.tellg();
is.seekg(0, ios::beg);
// จองหน่วยความจำ
char *buffer = new char[length];
// อ่านข้อมูลเป็นบล็อก
is.read(buffer, length);
// สร้าง string stream จากเนื้อหาในหน่วยความจำ
istringstream iss(string(buffer));
cout << buffer;
// ลบ buffer ชั่วคราว
delete[] buffer;
// ปิด filestream
is.close();
return 0;
}
ผลลัพธ์
hi tutorialspoint