我正在使用 spiri::qi
解析文本并将我解析的内容推送到 vector<string>
, 在大多数情况下它很好,因为它们主要是名称和地址,但也有一些我正在用 double_
解析的数字, 但是一旦我将它推到 vector
它认为它是一个字符代码,如 '\x3'
代替3.0
.我不想使用 variant
因为对于少数情况来说它的工作量太大了。无论如何我可以转换 double_
的结果吗?至 string
在插入它之前?
最佳答案
使用raw[double_]
(或者更准确地说是as_string[raw[double_]]
)。
第一个规则的工作方式与任何具有与字符容器的属性兼容性 的规则一样。后者以原子方式公开一个 std::string
(也有一个用于 std::wstring
)。
奖金
要完成 Jonathan Mee 关于“只使用语言”(释义...:))的建议,您可以,请参阅下面的最后一个演示语法:
#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
不会产生文字输入,因此它可能无法忠实地满足您的目的。
关于c++ - 如何从 qi::double_ 转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34397984/