c++ - 如何使用 boost::spirit::qi::parse 从字符数组中解析 double

标签 c++ c++11 boost-spirit

我可以从存储在 std::string、std::vector 或 std::array 中的字符解析数字。 但是当字符位于 std::unique_ptr 中的缓冲区中时,我无法这样做。 我可以将缓冲区复制到一个字符串中以提振精神,但我想避免这种复制

这是我的尝试:

#include<memory>
#include<array>
#include<iostream>
#include "boost/spirit/include/qi.hpp"


int main()
{
    const int max_size = 40;
    std::array<wchar_t, max_size> numeric1;
    std::wstring src = L"5178120.3663";
    std::wcsncpy(numeric1.data(), src.data(), max_size);

    double num = 0.0;
    boost::spirit::qi::parse(numeric1.begin(), numeric1.end(), num);
    std::cout.precision(15);
    std::cout << num << std::endl; // OK

    std::unique_ptr<wchar_t[]> numeric2(new wchar_t[max_size]);
    std::wcsncpy(numeric2.get(), src.data(), max_size);
    std::wcout << L"ok = " << std::wstring(numeric2.get()) << std::endl; // OK

    boost::spirit::qi::parse(numeric2.data(), max_size, num); // fails to compile 
    std::cout.precision(15);
    std::cout << num << std::endl;

    //  'boost::spirit::qi::parse': no matching overloaded function found

    return 0;
}

修复:

boost::spirit::qi::parse(numeric2.get(), numeric2.get() + wcslen(numeric2.get()), num);

查看 Zalman 的回答

最佳答案

boost::spirit::qi::parse 采用开始和结束迭代器。你可能想要这样的东西:

boost::spirit::qi::parse(numeric2.get(), numeric2.get() + wcsnlen(numeric2.get(), max_size), num);

即普通指针用作迭代器,您可以通过添加到开始指针来形成结束指针。

关于c++ - 如何使用 boost::spirit::qi::parse 从字符数组中解析 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46595026/

相关文章:

c++ - C++ 中高效的 Sum 和 Assignment 运算符重载

c++ - 注释期间和之后的 AST 排列

c++ - 对 double 的二维 vector 进行排序

c++ - 多重继承错误 'invalid use of incomplete type'

c++ - 用多个线程填充 vector

c++ - 如何使一个函数的返回类型与另一个函数的返回类型相同?

c++ - Boost Spirit 罗马数字解析器示例

c++ - 如何获取 boost.spirit 数字解析器匹配的子字符串?

c++ - 当存储为变量时,c++ find()返回不同的值

c++ - std::vector 应该尊重 alignof(value_type) 吗?