Wie analysieren wir end-of-line mit boost :: spirit :: Qi?
-
19-09-2019 - |
Frage
Soll nicht ein einfaches eol
den Trick tun?
#include <algorithm>
#include <boost/spirit/include/qi.hpp>
#include <iostream>
#include <string>
using boost::spirit::ascii::space;
using boost::spirit::lit;
using boost::spirit::qi::eol;
using boost::spirit::qi::phrase_parse;
struct fix : std::unary_function<char, void> {
fix(std::string &result) : result(result) {}
void operator() (char c) {
if (c == '\n') result += "\\n";
else if (c == '\r') result += "\\r";
else result += c;
}
std::string &result;
};
template <typename Parser>
void parse(const std::string &s, const Parser &p) {
std::string::const_iterator it = s.begin(), end = s.end();
bool r = phrase_parse(it, end, p, space);
std::string label;
fix f(label);
std::for_each(s.begin(), s.end(), f);
std::cout << '"' << label << "\":\n" << " - ";
if (r && it == end) std::cout << "success!\n";
else std::cout << "parse failed; r=" << r << '\n';
}
int main() {
parse("foo", lit("foo"));
parse("foo\n", lit("foo") >> eol);
parse("foo\r\n", lit("foo") >> eol);
}
Ausgabe:
"foo": - success! "foo\n": - parse failed; r=0 "foo\r\n": - parse failed; r=0
Warum die beiden letzteren nicht?
Verwandte Frage:
Mit boost :: spirit, wie ich Teil eines Datensatzes erfordern auf seine eigene Linie zu sein?
Lösung
Sie verwenden space
als Skipper für Ihre Anrufe zu phrase_parse. Dieser Parser jedes Zeichen für die std::isspace
gibt true zurück (vorausgesetzt, Sie tun ascii basierte Analyse). Aus diesem Grunde sind die \r\n
in dem Eingang von Ihrem Skipper gegessen, bevor sie von Ihrem eol
Parser zu sehen.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow