参考: スラスラわかるC++ 第2版, pp.352-353
fstream
をインクルードする。fはfileのf。
ifstream インスタンス名("ファイルパス")
でifstream
クラスをインスタンス化する。これで読み込み元のファイルがひらかれる。
ifstream
の"if"は"input file"。
#include <iostream> #include <fstream> #include <string> using namespace std; int main(){ string s; // 読み出したテキストを格納するためのstring型変数sを宣言しておく。 ifstream neko("sute.txt"); // 読み込み元のファイルsute.txtをnekoという名前でインスタンス化する。 if (!neko.is_open()) { // 読み込み元のファイルが開けなかったら、 cout << "cannot be opened."; // 何かをコンソールに表示して、 return 1; // 何かを返してmain()を抜ける。 } while (getline(neko, s)) { // 1行読み込めたら、 cout << s << endl; // その1行をコンソールに出力するが、 } // 読み込む行がなくなったら、 neko.close(); // ファイルを閉じて、 return 0; // main()を抜ける。 }