2010-12-30 13 views
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, 
のような

ヘッダーがない場合、プログラムは正常に動作します。ヘッダーを削除して出力ファイルに挿入するにはどうすればよいのですか?どのように同じ書式を保持できますか?

私はどこかからこのコードを採用しました。私はソースを覚えていません。

答えて

2

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

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

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

+0

例を挙げることができます。ありがとう –

関連する問題