c – 在Boost Spirit中解码char UTF8转义

提问: Spirit-general list

大家好,

我不确定我的主题是否正确,但测试代码可能会显示
我想要实现的目标.

我正在尝试解析以下内容:

>’@’到’@’
>’<'到'<'
我在下面有一个最小的测试用例.我不明白为什么
这不起作用.这可能是我犯了一个错误,但我没有看到它.

使用:
编译器:gcc 4.6
提升:当前主干

我使用以下编译行:

g++ -o main -L/usr/src/boost-trunk/stage/lib -I/usr/src/boost-trunk -g -Werror -Wall -std=c++0x -DBOOST_SPIRIT_USE_PHOENIX_V3 main.cpp
#include <iostream>
#include <string>

#define BOOST_SPIRIT_UNICODE

#include <boost/cstdint.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/phoenix/phoenix.hpp>

typedef boost::uint32_t uchar; // Unicode codepoint

namespace qi = boost::spirit::qi;

int main(int argc,char **argv) {

    // Input
    std::string input = "%3C";
    std::string::const_iterator begin = input.begin();
    std::string::const_iterator end = input.end();

    using qi::xdigit;
    using qi::_1;
    using qi::_2;
    using qi::_val;

    qi::rule<std::string::const_iterator,uchar()> pchar =
        ('%' > xdigit > xdigit) [_val = (_1 << 4) + _2];

    std::string result;
    bool r = qi::parse(begin,end,pchar,result);
    if (r && begin == end) {
        std::cout << "Output:   " << result << std::endl;
        std::cout << "Expected: < (LESS-THAN SIGN)" << std::endl;
    } else {
        std::cerr << "Error" << std::endl;
        return 1;
    }

    return 0;
}

问候,

MatthijsMöhlmann

解决方法

qi :: xdigit没有做你认为它做的事情:它返回原始字符(即’0′,而不是0x00).

你可以利用qi::uint_parser来获得优势,使你的解析更加简单:

typedef qi::uint_parser<uchar,16,2,2> xuchar;

>不需要依赖凤凰(使其适用于较旧版本的Boost)
>一次性获取两个字符(否则,您可能需要添加大量的转换以防止整数符号扩展)

这是一个固定的样本:

#include <iostream>
#include <string>

#define BOOST_SPIRIT_UNICODE

#include <boost/cstdint.hpp>
#include <boost/spirit/include/qi.hpp>

typedef boost::uint32_t uchar; // Unicode codepoint

namespace qi = boost::spirit::qi;

typedef qi::uint_parser<uchar,2> xuchar;
const static xuchar xuchar_ = xuchar();


int main(int argc,char **argv) {

    // Input
    std::string input = "%3C";
    std::string::const_iterator begin = input.begin();
    std::string::const_iterator end = input.end();

    qi::rule<std::string::const_iterator,uchar()> pchar = '%' > xuchar_;

    uchar result;
    bool r = qi::parse(begin,result);

    if (r && begin == end) {
        std::cout << "Output:   " << result << std::endl;
        std::cout << "Expected: < (LESS-THAN SIGN)" << std::endl;
    } else {
        std::cerr << "Error" << std::endl;
        return 1;
    }

    return 0;
}

输出:

Output:   60
Expected: < (LESS-THAN SIGN)

‘<’确实是ASCII 60

相关文章

一.C语言中的static关键字 在C语言中,static可以用来修饰局...
浅谈C/C++中的指针和数组(二) 前面已经讨论了指针...
浅谈C/C++中的指针和数组(一)指针是C/C++...
从两个例子分析C语言的声明 在读《C专家编程》一书的第三章时...
C语言文件操作解析(一)在讨论C语言文件操作之前,先了解一下...
C语言文件操作解析(三) 在前面已经讨论了文件打开操作,下面...