C++ Wiki

2015.04.25

Tags: STL

std::fstreamでファイルのリード

std::getlineで1行の読み込み、operator>>で簡易パーサーのような感じで読み込みができます。

サンプルコード

#include <iostream>
#include <fstream>
#include <string>

int main()
{
  std::ifstream f("data.txt");
  if(!f){
    std::cout << "fail to open" << std::endl;
    return 1;
  }

  std::string s;
  std::getline(f, s);
  std::cout << s << std::endl;

  for(;;){
    int a, b, c;
    f >> a >> b >> c;
    if(f.good()){
      std::cout << "a=" << a << " b=" << b << " c=" << c << std::endl;
    }
    else{
      break;
    }
  }

  return 0;
}

データファイル (data.txt)

abcde efg
12 34
56 78 90
123

実行結果

abcde efg
a=12 b=34 c=56
a=78 b=90 c=123