[英]What is the best way to create a vector of meaningful data out of a comma delimited text file
Consider the following: 考虑以下:
I have a class defined : 我有一个类定义:
class Human
{
public:
std::string Name;
std::string Age;
std::string Weight;
}
I have a .txt file defined: 我定义了一个.txt文件:
Justin,22,170
Jack,99,210
Fred,12,95
etc...
The goal is to turn this text file into a std::vector 目标是将此文本文件转换为std :: vector
My current code is as follows: 我目前的代码如下:
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;
}
}
}
Now i'm just curious is there any c++11 technique or non c++11 technique that would be more efficient / easier to read then this? 现在我只是好奇是否有任何c ++ 11技术或非c ++ 11技术更高效/更容易阅读呢?
I write a skeleton version, it should work with line base structure: 我写了一个骨架版本,它应该与行基础结构一起使用:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.