-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.cpp
More file actions
67 lines (60 loc) · 1.76 KB
/
main.cpp
File metadata and controls
67 lines (60 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// To view the license please visit
// https://github.com/IDNI/parser/blob/main/LICENSE.md
// CSV parser tutorial - part 4
//
// In this part we enhance the parser for parsing also negative integers.
#include <optional>
#include <limits>
#include "parser.h"
#ifdef min
# undef min
#endif
#ifdef max
# undef max
#endif
using namespace std;
using namespace idni;
struct csv_parser {
csv_parser() :
cc(predefined_char_classes({ "digit" }, nts)),
start(nts("start")), digit(nts("digit")),
// add digits nonterminal which represents a sequence of digits
digits(nts("digits")),
g(nts, rules(), start, cc), p(g) {}
optional<int_t> parse(const char* data, size_t size) {
auto res = p.parse(data, size);
optional<int_t> i{};
if (!res.found) return cerr << res.parse_error << '\n', i;
i = res.get_terminals_to_int(res.get_forest()->root());
if (!i) return cerr << "out of range, allowed range is from: "
<< numeric_limits<int_t>::min() << " to: "
<< numeric_limits<int_t>::max() << '\n', i;
return i;
}
private:
nonterminals<> nts;
char_class_fns<> cc;
prods<> start, digit, digits;
grammar<> g;
parser<> p;
prods<> rules() {
prods<> r, minus('-'); // create a minus terminal for '-'
// digits is a sequence of digits (was start in previous part)
r(digits, digit | (digit + digits));
// start now can be a sequence of digits or the minus terminal
// followed by a sequence of digits
r(start, digits | (minus + digits));
return r;
}
};
int main() {
cout << "Validator for integers. "
<< "Enter an integer per line or Ctrl-D to quit\n";
csv_parser p;
string line;
while (getline(cin, line)) {
cout << "entered: `" << line << "`\n";
auto i = p.parse(line.c_str(), line.size());
if (i) cout << "parsed integer: " << i.value() << '\n';
}
}