请考虑以下事项:
我定义了一个类:
class Human
{
public:
std::string Name;
std::string Age;
std::string Weight;
}
我定义了一个.txt文件:
Justin,22,170
Jack,99,210
Fred,12,95
etc...
目标是将此文本文件转换为std :: vector
我目前的代码如下:
vector<Human> vh;
std::ifstream fin(path);
std::string line;
while(std::getline(fin,line))
{
std::stringstream linestream(line);
std::string value;
Human h;
int IntSwitch = 0;
while(getline(linestream,value,','))
{
++IntSwitch;
try{
switch(IntSwitch)
{
case 1 :
h.Name = value;
break;
case 2:
h.Age = value;
break;
case 3:
h.Weight = value;
vh.push_back(h);
break;
}
}
catch(std::exception ex)
{
std::cout << ex.what() << std::endl;
}
}
}
现在我很好奇是否有任何c ++ 11技术或非c ++ 11技术可以更高效/更容易阅读呢?
答案 0 :(得分:1)
我写了一个骨架版本,它应该与行基础结构一起使用:
struct Human
{
Human(const std::string& name, const std::string& age, const std::string& weight)
: name_(name), age_(age), weight_(weight) { }
std::string name_;
std::string age_;
std::string weight_;
};
class CSVParser
{
public:
CSVParser(const std::string& file_name, std::vector<Human>& human) : file_name_(file_name)
{
std::ifstream fs(file_name.c_str());
std::string line;
while(std::getline(fs, line))
{
human.push_back(ConstructHuman(line));
}
}
Human ConstructHuman(const std::string& line);
private:
std::string file_name_;
};
Human CSVParser::ConstructHuman(const std::string& line)
{
std::vector<std::string> words;
std::string word;
std::stringstream ss(line);
while(std::getline(ss, word, ','))
{
words.push_back(word);
}
return Human(words[0], words[1], words[2]);
}
int main()
{
std::vector<Human> human;
CSVParser cp("./word.txt", human);
return 0;
}