[英]How to set class objects from vector of string in c++
這些是我的Login.csv文件中的數據:
身份證,姓名,密碼,性別
1,利亞姆,1234,M
2,詹妮絲,0000,F
所以可能我將使用類和對象創建登錄詳細信息,並將其寫入文件。 之后,我將csv從文件拆分為字符串向量,然后從那里將細節加載回類對象。
這是我從文件中拆分csv的代碼:
int _tmain(int argc, _TCHAR* argv[])
{
string line;
ifstream fin("users.csv");
while (getline(fin, line)){
vector<string> token;
split(line, ',', token);
for (int i = 0; i < token.size(); i++){
cout << token[i] << " ";
//////////// <<here>>
}
cout << endl;
}
system("pause");
return 0;
}
void split(const string& s, char c, vector<string>& v) {
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos) {
v.push_back(s.substr(i, j - i));
i = ++j;
j = s.find(c, j);
if (j == string::npos)
v.push_back(s.substr(i, s.length()));
}
}
我在想如何設置從字符串向量到對象向量的分割后的字符串,就像這樣:(放在我在上面評論的《這里》中)
vector<Login>loginVector;
//all the objects below should set from string vector (token)
loginVector[i].setID(); //i=0, id=1, name=Liam, password=1234, gender=M
loginVector[i].setName();
loginVector[i].setPassword();
loginVector[i].setGender();
loginVector[i].setID(); //i=1, id=2, name=Janice, password=0000, gender=M
loginVector[i].setName();
loginVector[i].setPassword();
loginVector[i].setGender();
謝謝。
實現您的Login
對象並在循環中填充它。
struct Login {
enum Gender {
Male,
Female
};
int Id;
std::string Name;
std::string Password;
/* you should probably use a constructor */
};
/* to construct your vector */
int I = 0;
while(I < token.size()) {
/* in your iterator */
Login& LO = loginVector.emplace_back(Login{});
LO.Id = std::stoi(token[++I]);
LO.Name = token[++I];
/* etc...*/
}
請注意,這假設您的CSV格式正確,可以由您實施所有檢查,並確保您處理諸如stoi
,空白行或缺少列的可能錯誤之類的stoi
情況。
另外,不要執行system("pause");
,您正在執行一個shell來為您睡眠,與僅使用sleep
實際上會做同樣的事情相比,這有很多開銷,只是以更直接的方式。
我個人將通過為您的班級添加提取運算符來實現此目的。 您必須與提取運算符成為friend
,因為它必須在類的外部定義,因為它實際上是在istream
而不是在您的類上進行操作,因此應在類中定義以下內容:
friend istream& operator>> (istream& lhs, Login& rhs);
根據變量的命名方式,提取運算符應如下所示:
istream& operator>> (istream& lhs, Login& rhs) {
char gender;
lhs >> rhs.id;
lhs.ignore(numeric_limits<streamsize>::max(), ',');
getline(lhs, rhs.name, ',');
getline(lhs, rhs.password, ',');
lhs >> ws;
lhs.get(gender);
rhs.isMale = gender == 'm' || gender == 'M';
return lhs;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.