透過 C++ 類進行檔案處理


在本教程中,我們將討論一個程式,以理解透過 C++ 類進行檔案處理。

使用者可以使用類定義檔案處理中用於與檔案互動的預設函式。以下是 ifstream 和 ofstream 函式的實現。

示例

#include <iostream>
#include <fstream>
using namespace std;
int main(){
   //creating ofstream object ofstream fout;
   string line;
   fout.open("sample.txt");
   //initiating loop if file is opened
   while (fout) {
      getline(cin, line);
      if (line == "-1")
         break;
      fout << line << endl;
   }
   fout.close();
   ifstream fin;
   fin.open("sample.txt");
   while (fin) {
      getline(fin, line);
      cout << line << endl;
   }
   fin.close();
   return 0;
}

更新於:2020-03-23

795 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.