-
Notifications
You must be signed in to change notification settings - Fork 246
Expand file tree
/
Copy pathsum.cpp
More file actions
72 lines (60 loc) · 1.77 KB
/
sum.cpp
File metadata and controls
72 lines (60 loc) · 1.77 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
68
69
70
71
72
// Copyright (c) 2014-2026 Dr. Colin Hirsch and Daniel Frey
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <tao/pegtl.hpp>
#include <tao/pegtl/example/fp.hpp>
namespace pegtl = TAO_PEGTL_NAMESPACE;
namespace example
{
struct padded_double
: pegtl::pad< pegtl::fp::value, pegtl::space >
{};
struct double_list
: pegtl::list< padded_double, pegtl::one< ',' > >
{};
struct grammar
: pegtl::seq< double_list, pegtl::eof >
{};
template< typename Rule >
struct action
: pegtl::nothing< Rule >
{};
template<>
struct action< pegtl::fp::value >
{
template< typename ActionInput >
static void apply( const ActionInput& in, double& sum )
{
// assume all values will fit into a C++ double
std::stringstream ss( in.string() );
double v;
ss >> v;
sum += v;
}
};
} // namespace example
int main()
{
std::cout << "Give me a comma separated list of numbers.\n";
std::cout << "The numbers are added using the PEGTL.\n";
std::cout << "Type [q or Q] to quit\n\n";
std::string str;
while( !std::getline( std::cin, str ).fail() ) {
if( str.empty() || str[ 0 ] == 'q' || str[ 0 ] == 'Q' ) {
break;
}
double d = 0.0;
pegtl::view_input< void, char, std::string > in( "std::cin", str );
if( pegtl::parse< example::grammar, example::action >( in, d ) ) {
std::cout << "parsing OK; sum = " << std::setprecision( 12 ) << d << std::endl;
}
else {
std::cout << "parsing failed" << std::endl;
}
}
}