使用raw[double_](或更准确地说是as_string[raw[double_]])。
第一个规则与任何具有与字符容器的属性兼容性的规则类似。后者以原子方式公开std::string(std::wstring 也有一个)。
奖金
要完成 Jonathan Mee 的“只使用语言”的建议(释义... :))您可以,请参阅下面的最后一个演示语法:
Live On Coliru
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
namespace qi = boost::spirit::qi;
namespace px = boost::phoenix;
int main() {
using It = std::string::const_iterator;
auto to_string_f = [](auto v) { return std::to_string(v); };
px::function<decltype(to_string_f)> to_string_ { to_string_f };
for (std::string const input : { "3.14", "+inf", "NaN", "-INF", "99e-3" })
{
for (auto const& grammar : std::vector<qi::rule<It, std::string()>> {
//qi::double_, // results in strange binary interpretations, indeed
qi::raw[ qi::double_ ],
qi::as_string [ qi::raw[ qi::double_ ] ],
qi::double_ [ qi::_val = to_string_(qi::_1) ],
})
{
auto f = input.begin(), l = input.end();
std::string result;
if (qi::parse(f, l, grammar, result))
std::cout << input << "\t->\t" << result << "\n";
else
std::cout << "FAILED for '" << input << "'\n";
}
}
}
打印
3.14 -> 3.14
3.14 -> 3.14
3.14 -> 3.140000
+inf -> +inf
+inf -> +inf
+inf -> inf
NaN -> NaN
NaN -> NaN
NaN -> nan
-INF -> -INF
-INF -> -INF
-INF -> -inf
99e-3 -> 99e-3
99e-3 -> 99e-3
99e-3 -> 0.099000
请注意,std::to_string 不会产生文字输入,因此它可能无法忠实地为您的目的往返。