将.csv文件转换为C ++算法中的结构

时间:2013-12-13 13:22:15

标签: c++ algorithm structure

我想将.csv文件读入c ++代码,然后将文本数据转换为结构..我可以编写一个算法来读取.csv文件,但我将如何将其保存到结构中... .. csv文件中的数据在excel单元格中,第1列包含纬度,第2列包含经度,第3列包含分支代码,第4列包含地址,有7000行包含不同的位置和地址..我需要保存这些成为C ++算法的结构

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main () {
    string line;
    ofstream myfile;
    myfile.open("burgerking.csv");
    if(myfile.is_open()){
    cout<<"The file is open"<<endl;
    while (getline(myfile,line)) {
        cout << line << '\n';
        }
    }    
    myfile.close();
    system("PAUSE");
    return 0;
}

2 个答案:

答案 0 :(得分:0)

存储相互关联结构的一种(好)方法是使用索引:

你不能/不应该写入文件the struct at memory-address 0x12345678,但你可以写this is struct 181 and its first reference goes to struct 912, its second ref goes to...

它可以有效地完成:有一个hashmap,它将struct-pointers映射到你为它们选择的索引,每次你编写一个指针而不是写索引。

答案 1 :(得分:0)

#include <iostream>
#include <sstream> 
#include <fstream> 
#include <vector> 
#include <string.h>
#include "link1.h"
using namespace std;

class struc{

        link1 l1;

    public:
    struc()
    {
        string lat,lon, addr;
         string state1="\0";
        string state;
        l1.link1();
    ifstream inFile ("burgerking.csv"); 
    string line; 
    int linenum = 0;
    while (getline (inFile, line)) 
    { 
    linenum++; 
    cout << "\nLine #" << linenum << ":" << endl; 
    istringstream linestream(line); 
    string item; 
    int itemnum = 0;
    while (getline (linestream, item, ',')) 
    { 
    lat=item;
    break;}
    while (getline (linestream, item, ',')) 
    { 

    lon=item; 
    break;
        }
    while (getline (linestream, item, ',')) 
    { 

    addr=item;
     break;
        }
    while (getline (linestream, item, ',')) 
    { 
    state=item; 

     break;

    // cout<<lat<<endl<<lon<<endl<<addr<<endl<<state<<endl;


     }
     if(state1==state)
     break;
     else
     l1.add(state);
     state1=state;


    }
    }
    void disp()
    {
l1.display();
}};
////// Hey man please contact me ASAP skype:mrwaleedahmed i have got the same task as a   project so need a little bit of help