c++ - 如何从 qi::double_ 转换为字符串?

标签 c++ parsing boost type-conversion boost-spirit-qi

我正在使用 spiri::qi解析文本并将我解析的内容推送到 vector<string> , 在大多数情况下它很好,因为它们主要是名称和地址,但也有一些我正在用 double_ 解析的数字, 但是一旦我将它推到 vector它认为它是一个字符代码,如 '\x3'代替3.0 .我不想使用 variant因为对于少数情况来说它的工作量太大了。无论如何我可以转换 double_ 的结果吗?至 string在插入它之前?

最佳答案

使用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 不会产生文字输入,因此它可能无法忠实地满足您的目的。

关于c++ - 如何从 qi::double_ 转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34397984/

相关文章:

c++ getline 似乎无法识别通过管道传输到标准输入的输入中的换行符

regex - 使用Powershell和Regex解析固定长度的字段文件,如何将空捕获组替换为零?

parsing - 如何使用 BNFC 定义 INI 文件语法?

c++ - 操作系统 : Linker error for boost/filesystem with Xcode 8 and C++ 11

c++ - 如何检查套接字是否在 Boost.Asio 中关闭?

c++ - 作者对用户定义类型的输入的评论是什么意思?

c++ - 如何实现自定义的类似 ostringstream 的格式化状态?

c++ - LLVMContext 作为类成员会破坏构造函数吗?

parsing - Go中如何高效方便的解析一条简单的消息?

c++ - 尝试将 boost::stacktrace 添加到 CMake 项目时生成错误