1

csv ファイルがあり、次のようにファイルを読み取ります。

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;

typedef vector <double> record_t;
typedef vector <record_t> data_t;
data_t data;

istream& operator >> ( istream& ins, record_t& record )
  {
  record.clear();

  string line;
  getline( ins, line );

  // Using a stringstream to separate the fields out of the line
  stringstream ss( line );
  string field;
  while (getline( ss, field, ',' ))
    {
    // for each field we wish to convert it to a double
    stringstream fs( field );
    double f = 0.0;  // (default value is 0.0)
    fs >> f;

    // add the newly-converted field to the end of the record    record.push_back( f );
    }
  return ins;
  }

//-----------------------------------------------------------------------------
istream& operator >> ( istream& ins, data_t& data )
  {
  data.clear();

  record_t record;
  while (ins >> record)
    {
    data.push_back( record );
    }
  return ins;
  }
//----------------------------------------------
int main() {
  ifstream infile( "2010.csv" );
  infile >> data;

  if (!infile.eof())
    {
    cout << "Error with the input file \n";
    return 1;
    }

  infile.close();

  //do something with "data"

  // write the data to the output.
}

今私が使用しているファイルは次のようなものです

A,B,c,D,E,F
1,1,1,1,1,1,
2,2,2,2,2,2,
3,3,3,3,3,3,

したがって、ヘッダーが存在しない場合、プログラムは正常に動作します。ヘッダーを削除して出力ファイルに戻すにはどうすればよいですか? また、同じフォーマットを維持するにはどうすればよいですか?

このコードはどこかから改作しましたが、ソースを覚えていません。

4

2 に答える 2

2

最初の行を最初に読み込んでから、ストリーム バッファをこの関数に入れるのはどうですか? 機能を変更したくないようです。

ifstream infile( "2010.csv" );
string header;
std::getline(infile, header);
infile >> data;
于 2010-12-30T19:58:31.533 に答える
2

最初の行に別の文字列を使用し、while ループでは、最初の行を特別なケースとして扱います (他のすべての行の通常の処理をスキップします)。

于 2010-12-30T19:00:28.810 に答える