テキストファイルから何かを読み込む

参考: スラスラわかる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()を抜ける。
}

f:id:ti-nspire:20190606051017p:plain
f:id:ti-nspire:20190606051452p:plain