LoginSignup
2

More than 5 years have passed since last update.

C++、STLでCSVを料理する

Last updated at Posted at 2016-07-12
C++
std::ifstream ifs( "hoge.csv" );
std::string line;
while ( std::getline( ifs, line ) ) {
  std::istringstream iss( line );
  std::string newCell;
  while( std::getline( iss, newCell, ',' ) ) {
    if ( newCell.length() > 0 ) {
      // TODO : セルにデータがあるから処理
    }
  }
}

外側のwhileでファイルストリームから行を丸ごとstringとして取り込み、内側のwhileでその行をストリングストリームにして、カンマ単位で文字列を取り込んでいく。
CSVにありがちな、行毎に列数が違った場合にカンマだけが続く状態に対応するため、取り込んだ文字列の文字列長が0じゃない場合のみ何かをする感じで書いてみました。

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
2