开发者

removing first line of a file and inserting it back in the output

I've a csv file and I read the file as follows:

#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 开发者_如何学Go>> 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.
}

Now the file I'm using is like

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

So if the header is not there the program works fine. How can I remove the header and insert it back to the output file and how can I keep the same formatting ?

I adapted this code from somewhere and I don't remember the source.


What about read the first line first, and then put the stream buffer into this function? It seems like you don't want to change the function.

ifstream infile( "2010.csv" );
string header;
std::getline(infile, header);
infile >> data;


Just use another string for the first line and in the while loop, treat the first line as a special case (skipping the normal processing for all other lines).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜