在 C++ 中將整個檔案讀入 std::string 的最佳方式是什麼?


這是將整個檔案讀入 C++ 中 std::string 的一種簡單方法

演算法

Begin
   Take the filename as inputstream.
   Declare a string variable str.
   Read the file till the end by using rdbuf().
   Put the data into st.
   Print the 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

更新於: 2019 年 7 月 30 日

2K+ 瀏覽量

開啟你的 事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.