【发布时间】:2011-07-04 09:28:17
【问题描述】:
解析这样的一行最好的方法是什么(元素的数量不固定):
[ 0.0125, 2.9518e+02, 1.2833e+00, -3.5302e-04, 1.2095e+01, 1.0858e-01, 1.2112e-04, 1.1276e+03 ] # comments
在 c++ 中获得double 的std::vector?我已经这样做了:
vector<double> read_line(string line)
{
vector<double> coefficients_line;
// erase all before [ and all after ]
size_t found1 = line.find("[");
if (found1 == string::npos) cerr << "line not valid: " << line;
line.erase(line.begin(), line.begin() + found1 + 1);
size_t found2 = line.find("]");
if (found2 == string::npos) cerr << "line not valid: " << line;
line.erase(line.begin() + found2, line.end());
vector<string> coefficients_string;
boost::split(coefficients_string, line, boost::is_any_of(","));
for (vector<string>::const_iterator ic=coefficients_string.begin();
ic!=coefficients_string.end(); ++ic)
{
cout << "c string \"" << *ic << "\"" << endl;
string s = *ic;
boost::trim(s);
double c = boost::lexical_cast<double>(s);
cout << "c double: " << c << endl;
coefficients.push_back(c);
}
return coefficients;
}
欢迎使用非增强但简单的解决方案
【问题讨论】:
标签: c++ string parsing tokenize