將整個 ASCII 檔案讀入 C++ std::string


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

演算法

Begin
   Declare a file a.txt using file object f of ifstream type to perform read operation.
   Declare a variable str of string type.
   If(f)
      Declare another variable ss of ostringstream type.
      Call rdbuf() fuction to read data of file object.
      Put the data of file object in ss.
      Put the string of ss into the str string.
   Print the value of str.
End.

示例

#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
int main() {
   ifstream f("a.txt"); //taking file as inputstream
   string str;
   if(f) {
      ostringstream ss;
      ss << f.rdbuf(); // reading data
      str = ss.str();
   }
   cout<<str;
}

輸入

a.txt data file containing the text “hi”

輸出

hi

更新時間: 2020 年 6 月 24 日

1.4 萬+ 次瀏覽

開啟你的 職業生涯

透過完成該課程獲得認證

入門
廣告