2010-12-30 7 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

예를 들려 줄 수 있습니다. 감사 –

관련 문제