我有一个 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,
因此,如果标题不存在,则程序可以正常工作。如何删除标题并将其插入回输出文件,如何保持相同的格式?
我从某个地方改编了这段代码,但我不记得来源了。