【发布时间】:2018-10-21 16:00:26
【问题描述】:
我有下一个名为“Contact”的 c++ 类:
class Contact
{
private:
std::string contactName;
double subscriptionPrice;
int minutesIncluded;
public:
Contact(const std::string &contactName, double subscriptionPrice,
int minutesIncluded) : contactName(contactName), subscriptionPrice(subscriptionPrice), minutesIncluded(minutesIncluded)) {}
Contact() {
}
...gettetrs and setters
}
我有一个包含一个或多个联系人的文本文件,格式为:
asd,1.00000,1
在主要方法中,我有在此文本文件中正确添加联系人向量的方法。问题是当我尝试从中读取时。我的目标是将文本文件转换为联系人向量。我使用的方法是下一个:
void phonebook_load(vector<Contact> &contacts)
{
string line;
ifstream phonebook_file;
vector<std::string> lines;
phonebook_file.open(phonebook_filename);
if(!phonebook_file.is_open())
cout << "Phonebook file could not be openned !!!" << endl;
else
{
while (phonebook_file.good())
{
for (string line; getline(phonebook_file, line, ','); )
lines.push_back(line);
}
phonebook_file.close();
}
}
我有两个选择:
- 逐行阅读(不能用“,”分割)
- 按“,”分割,在新行上打印联系人的每个属性,我不知道如何从那里处理它。
为了逐行读取文件并将其正确转换为vector<Contact>,我应该在我的方法中进行哪些更改
【问题讨论】:
-
fscanf(ww,"%s,%f,%d%*c",...) ;
标签: c++ vector concatenation ofstream