ファイルを一度に読み込む方法

Jupyterを使ってC++を勉強しています。


Jupyter上なので標準入力の代わりに、stringからデータを読み込んであとの処理で使う、という方法をとっているのですが、テキストファイルを一度に文字列に取り込めないかな、と思い、調べてみました。

c++ read entire text file into string

とかで検索したところ、

std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();

という解答があったので、Jupyterのセルで実験してみました。

# include <bits/stdc++.h>
using namespace std;
string s;
ifstream ifs("./mycpp/input.txt");
stringstream ss;
ss << ifs.rdbuf();
s = ss.str()

これで、変数 s の中にファイルinput.txtの内容が、空白や改行も含めて全部取り込まれました。

成功です。