นี่คือวิธีง่ายๆ ในการอ่านไฟล์ทั้งหมดเข้า std::string ใน C++
อัลกอริทึม
Begin
Take filename as input stream
Declare string variable str
Read file until end using rdbuf()
Put data into str
Print data
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;
}ข้อมูลนำเข้า
a.txt data file contains the string "hi"
ผลลัพธ์
hi