LoginSignup
4

More than 3 years have passed since last update.

c++ファイルの受け取り、読み込み[ifstream,getline]

Last updated at Posted at 2019-08-18

概要

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4