简体   繁体   English

删除文件的第一行并将其插回输出中

[英]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: 我有一个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.
}

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. 我从某个地方改编了这个代码,我不记得来源了。

只需在第一行和while循环中使用另一个字符串,将第一行视为特殊情况(跳过所有其他行的正常处理)。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM