如果你的“非数字”字符的字符串中的任何位置显示(即你的电话号码“1123 [456”),那么你无法逃避预处理字符串,并删除他们的中间。幸运的是,您可以使用std::copy_if
算法的std::remove_if
一次完成此操作。但是,如果您的“非数字”字符只出现在字符串的开头或结尾,则实际上可以将它们视为空格,并使用具有自定义语言环境的stringstream
正确“拆分”字符串。定义一个方面,将[
,]
和\t
作为空间,你很好去。这样做也会照顾到你的第二个问题 - 几个相邻的\t
个字符。
除了这个,你可以定义另一面,将治疗,
作为一个小数点。将它与前一个结合使用,您可以直接从原始字符串中读取double
。
下面是执行所有操作的代码。首先,方面:
struct custom_space_facet: std::ctype<char> {
custom_space_facet(const std::string& s): std::ctype<char>(get_table(s)) {}
static const std::ctype_base::mask* get_table(std::string const &s) {
static std::vector<std::ctype_base::mask> rc(table_size, std::ctype_base::mask());
for (auto ch : s) rc[ch] = std::ctype_base::space;
return &rc[0];
}
};
struct decimal_coma_facet : std::numpunct<char> {
char do_decimal_point() const { return ','; }
};
接下来,该代码本身:
auto l1 = std::locale(std::locale(), new custom_space_facet(" \t[]"));
auto l2 = std::locale(std::locale(), new decimal_coma_facet);
auto locale = l1.combine<std::numpunct<char>>(l2);
std::stringstream input("[12,75082301 28,53644171 119,392771] [108,4213282 30,04183776 77,14237388]");
input.imbue(locale);
std::cout << std::setprecision(10);
double value;
while (input >> value)
std::cout << value << "\n";
运行这会给你想要的双打:
12.75082301
28.53644171
119.392771
108.4213282
30.04183776
77.14237388
https://msdn.microsoft.com/en -us/library/hs600312%28v = vs.110%29.aspx –
你只是在说删除方括号,对不对?逗号看起来像是他们打算成为分数分隔符。 (我提到这一点,因为英语国家使用期限,而不是每个人都知道,许多其他文化用逗号。) – Wyzard
哦,是对不起,我忘了。逗号确实是分隔符! – Razero