Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Cách đọc nội dung file vào istringstream trong C++?

Chương trình C++ đọc nội dung file vào istringstream.

Ví dụ

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

int main() {
  ifstream is("a.txt", ios::binary);
  // lấy độ dài file:
  is.seekg(0, std::ios::end);
  long length = is.tellg();
  is.seekg(0, std::ios::beg);
  // cấp phát bộ nhớ:
  char *buffer = new char[length];
  // đọc dữ liệu như một khối:
  is.read(buffer, length);
  // tạo string stream từ nội dung bộ nhớ
  istringstream iss(string(buffer));
  cout << buffer;
  // xóa buffer tạm
  delete[] buffer;
  // đóng filestream
  is.close();
  return 0;
}

Kết quả

hi tutorialspoint