所以我有以下数据字符串,它是通过 TCP winsock 连接接收的,并且想做一个高级标记化,到一个结构向量中,其中每个结构代表一个记录。
std::string buf = "44:william:adama:commander:stuff\n33:luara:roslin:president:data\n"
struct table_t
{
std::string key;
std::string first;
std::string last;
std::string rank;
std::additional;
};
字符串中的每条记录都由回车符分隔。我尝试拆分记录,但尚未拆分字段:
void tokenize(std::string& str, std::vector< string >records)
{
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of("\n", 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of("\n", lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
// Found a token, add it to the vector.
records.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of("\n", pos);
// Find next "non-delimiter"
pos = str.find_first_of("\n", lastPos);
}
}
似乎完全没有必要再次重复所有代码以通过冒号(内部字段分隔符)将每个记录进一步标记到结构中并将每个结构推入向量中。我确信有更好的方法可以做到这一点,或者设计本身可能是错误的。
感谢您的任何帮助。