Cpp:将字符串片段解析为元组



我想将字符串片段解析为元组:示例字符串:";Dolly Davenell,8809903417,1 Toban Circle,罗州"元组<string,unsigned int,string,字符串>

我从文件中读取字符串,并将它们与getline一起存储在向量(myPersVec(中,其中每个向量元素都是如上所述的字符串。

现在我的问题是,我不知道如何分离每个字符串元素并将其填充到每个元组元素中。

我知道我可以用delimeter字符分隔字符串元素,但我如何将其解析为元组?然后我想将每个元组保存到另一个Vector(my2ndVec(中

我的问题是:一旦我有了字符串标记,我如何以正确的顺序将它们解析为一个元组?

auto makeT([](std::string line, std::vector<std::tuple<std::string, unsigned int, std::string, std::string>>& my2ndVec, std::vector<std::string> myPersVec) {
std::string token;
std::string deli = ",";
int pos = 0;
while ((pos = line.find(deli)) != std::string::npos) {
token = line.substr(0, pos);
std::cout << token << std::endl;
line.erase(0, pos + deli.length());
}
//how can i parse the tokens now into the tuple? and how do i parse them since i need to get multiple tokens
});
  1. 编辑:打字错误

有很多方法可以解析数据。您可以使用std::stringstreamfind或其他任何选项。我相信您要问的问题是如何将值直接存储到元组中。为此,使用std::get,它返回对元组中值的引用。

// Parameter s is the line to parse. Ex: "Dolly Davenell,8809903417,1 Toban Circle,Luozhou"
std::tuple<std::string, long, std::string, std::string> parse_line(std::string s)
{
std::stringstream ss(s);
std::tuple<std::string, long, std::string, std::string> t;
if (std::getline(ss, std::get<0>(t), ',')) {
if (ss >> std::get<1>(t)) {
ss.ignore(1);  // Skip comma
if (std::getline(ss, std::get<2>(t), ',') && std::getline(ss, std::get<3>(t))
return t;
}
}
}
// throw here or handle error somehow
}

我将int更改为long,因为示例中的值对于32位整数太大。

最新更新