Let's modify the trivial parser we just saw to ignore any spaces it might
find among the double
s and commas.
To skip whitespace wherever we find it, we can pass a skip parser
to our call to parse()
(we don't need to touch
the parser passed to parse()
).
Here, we use ws
, which matches
any Unicode whitespace character.
#include <boost/parser/parser.hpp> #include <iostream> #include <string> namespace bp = boost::parser; int main() { std::cout << "Enter a list of doubles, separated by commas. No pressure. "; std::string input; std::getline(std::cin, input); auto const result = bp::parse(input, bp::double_ % ',', bp::ws); if (result) { std::cout << "Great! It looks like you entered:\n"; for (double x : *result) { std::cout << x << "\n"; } } else { std::cout << "Good job! Please proceed to the recovery annex for cake.\n"; } }
The skip parser, or skipper, is run between the subparsers
within the parser passed to parse()
.
In this case, the skipper is run before the first double
is parsed, before any subsequent comma or double
is parsed, and at the end. So, the strings "3.6,5.9"
and " 3.6 , \t 5.9 "
are parsed the same by this program.
Skipping is an important concept in Boost.Parser. You can skip anything,
not just whitespace; there are lots of other things you might want to skip.
The skipper you pass to parse()
can be an arbitrary parser. For example, if you write a parser for a scripting
language, you can write a skipper to skip whitespace, inline comments, and
end-of-line comments.
We'll be using skip parsers almost exclusively in the rest of the documentation. The ability to ignore the parts of your input that you don't care about is so convenient that parsing without skipping is a rarity in practice.