2012-05-15 37 views
0

我上的地址簿程序,從以下格式的CSV文件中讀取數據時矢量型類(通訊錄計劃)

「姓」,「名」,「綽號」,「EMAIL1 」,‘EMAIL2’,‘PHONE1’,‘PHONE2’,‘地址’,‘網頁’,‘生日’,‘筆記’

我已閱讀下列方式使用函數getline文件:

if(!input.fail()) 
    { 
     cout<<"File opened"<<endl; 
     while(!input.eof()) 
     { 

    getline(input,list) ; 
    contactlist.push_back(list); 
    token=con.tokenize(list); // NOT SURE IF I'm doing this right..am I? 

     } 
    } 

我正在使用我的一個類聯繫人的tokenize成員函數,它看起來像th是

// member function reads in a string and tokenizes it 
vector<string>Contact::tokenize(string line) 
{ 
    int x = 0, y = 0,i=0; 

string token; 
vector<string>tokens; 
while(x < line.length() && y < line.length()) 
{ 

    x = line.find_first_not_of(",", y); 
    if(x >=0 && x < line.length()) 
    { 

     y = line.find_first_of(",", x); 
     token = line.substr(x, y-x); 
     tokens.push_back(token); 
     i++; 
    } 
} 

}  

我現在需要閱讀標記化矢量到另一個類的私有向量成員變量,也需要將它們讀入第一個名字的個人私有變量,姓氏...筆記類的Contact.How做我將它們讀入到一個類型的私有向量成員變量中,並且我將如何在成員函數中調用它們,這些成員函數將執行評估,例如使用向量添加聯繫人。

總共有2個頭文件聯繫人和地址簿及其各自的實現文件和主。

此外,如果你碰巧有一個清晰的概念訪問向量中向量/向量的向量像我有contactlist和令牌在這裏主要

回答

1

首先,你應該從接觸類分開你的令牌化功能。讀取csv行並不是聯繫人的責任。因此,將此方法提取到新的tokenizer類中,只需編寫一個自由標記化函數或使用像boost tokenizer這樣的解決方案。

使用生成的令牌,您可以創建聯繫人實例或將其傳遞給另一個類。

struct Contact 
{ 
    std::string firstName, lastName, email; 

    /// Constructor. 
    Contact(const std::string& firstName, 
     const std::string& lastName, 
     const std::string& email); 
}; 

struct AnotherClass 
{ 
    /// Constructor. 
    AnotherClass(const std::vector<std::string>& tokens) : 
    privateVector(tokens) {} 

    /// Construction with input iterators 
    template<typename Iter> 
    AnotherClass(Iter firstToken, Iter lastToken) : 
    privateVector(firstToken, lastToken) {} 

private: 
    std::vector<std::string> privateVector; 
}; 


int main() 
{ 
    std::string line = ReadLine(); 
    std::vector<std::string> tokens = tokenize(line); 

    Contact newContact(tokens[0], tokens[1], tokens[2]); 

    AnotherClass wathever(begin(tokens), end(tokens)); 
}