概要
C++でのファイルの受け取り、読み込みについて
久々にかくとわからなかったので、メモ
コード
入力として、以下のファイルを受け取る
test.tsv
1 3 5 7
2 4 6 8
ファイルの読み込みには、ifstreamを、行単位での読み込みにはgetlineを使う、(getlineはEOF(ファイルの終了)が出ると、0を返してくれるらしく、whileの条件式に書くだけで、自動で全行の読み込みができるみたいです。
file_read.cpp
# include <iostream>
# include <fstream>
# include <string>
using namespace std;
int main(int argc, char *argv[] ) {
ifstream ifs(argv[1]);// 第一引数のファイルを受け取り
// 行数を表示して出力する
int line_num = 1;
string line;
while (getline(ifs,line)){
cout << line_num << ":" << line << endl;
line_num += 1;
}
}
実行結果
$ ./a.out test.tsv
1:1 3 5 7
2:2 4 6 8