所以我有通過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);
}
}
似乎完全沒有必要再重複了代碼通過結腸進一步記號化每個記錄(內部字段分隔符)到結構:我分裂了記錄,但尚未分手了領域的嘗試並將每個結構體推送到一個向量中。我相信有這樣做的更好方法,或者設計本身可能是錯誤的。
謝謝你的幫助。
如果你可以使用提升,這將是相當整齊地做使用它的標記器庫,它的字符串算法庫,或者對於最強大的解決方案,使用'boost.spirit',如下所示:http://www.boost.org/doc/libs/1_46_1/libs/spirit/doc /html/spirit/qi/tutorials/employee___parsing_into_structs.html – Cubbi 2011-03-28 16:32:03
錯過了此評論。對於這種情況下使用的[數據格式太重的012] – user237419 2011-03-28 16:40:10
使用[boost :: tokenizer](http://www.boost.org/doc/libs/1_46_1/libs/tokenizer/index.html) – user237419 2011-03-28 16:38:34