4

提问: 精灵总表

大家好,

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

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

  • “%40”到“@”
  • '%3C' 到 '<'

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

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

我使用以下编译行:

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;
}

问候,

马蒂斯·莫尔曼

4

1 回答 1

2

qi::xdigit does not do what you think it does: it returns the raw character (i.e. '0', not 0x00).

You could leverage qi::uint_parser to your advantage, making your parse much simpler as a bonus:

typedef qi::uint_parser<uchar, 16, 2, 2> xuchar;
  • no need to rely on phoenix (making it work on older versions of Boost)
  • get both characters in one go (otherwise, you might have needed to add copious casting to prevent integer sign extensions)

Here is a fixed up sample:

#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, 16, 2, 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, 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;
}

Output:

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

'<' is indeed ASCII 60

于 2011-11-10T13:47:30.513 回答