我解析來自「純C」接口的文本數組,並且每個字符串可能有任意數量的值,可能孤立地被解析爲「istream::operator >>()
」。C++更好的方法來解析值到一個向量
例如,解析器之一是自定義的IPv4類:
std::istream & operator >>(std::istream& stream, IPv4 &var)
的實施是相當明顯的。
現在假設等的輸入:
const char *string_array[] =
{
"192.168.0.1, 192.168.0.32, 192.168.0.40",
"169.254.3.18, 169.254.3.19, 169.254.3.20, 169.254.3.21",
"10.0.92.100",
"10.0.0.101, 10.0.0.102, 10.0.0.103 , 10.0.0.104 , 10.0.0.110 ",
};
我想找到一種優雅的方式把所有的分析值的數組,這樣我可以把它給「C-只有」功能。
天真的方法將首先使用stringstream
將所有字符串(const char *
)控制在一起,然後用我的operator >>
循環播放此流。
std::stringstream ss;
IPv4 ip;
std::vector<IPv4> ip_vector;
for (int c = 0; c < count; ++c)
ss << string_array[ c ] << ", ";
while (ss.good())
{
ss >> ip;
ip_vector.push_back(ip);
}
這對我來說似乎並不明智,但我無法弄清楚如何讓這更聰明。
另請注意:Boost不是此解決方案的選項。
您確定您描述的方法正常嗎?您將所有字符串寫入沒有分隔符的流中,因此您最終可能會得到如下所示的片段:'192.168.0.40169.254.3.18'。 – dasblinkenlight 2012-07-13 19:35:28
是的,你是對的。我會修復我的例子,謝謝。 – j4x 2012-07-13 19:38:24