xref: /aosp_15_r20/external/libconfig/contrib/chained/examples/example2.cpp (revision 2e9d491483b805f09ea864149eadd5680efcc72a)
1 /* ----------------------------------------------------------------------------
2    libconfig - A library for processing structured configuration files
3    libconfig chained - Extension for reading the configuration and defining
4                        the configuration specification at once.
5    Copyright (C) 2016 Richard Schubert
6 
7    This file is part of libconfig contributions.
8 
9    This library is free software; you can redistribute it and/or
10    modify it under the terms of the GNU Lesser General Public License
11    as published by the Free Software Foundation; either version 2.1 of
12    the License, or (at your option) any later version.
13 
14    This library is distributed in the hope that it will be useful, but
15    WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17    Lesser General Public License for more details.
18 
19    You should have received a copy of the GNU Library General Public
20    License along with this library; if not, see
21    <http://www.gnu.org/licenses/>.
22    ----------------------------------------------------------------------------
23 */
24 
25 #include <iostream>
26 #include <iomanip>
27 #include <cstdlib>
28 #include "../libconfig_chained.h"
29 
30 using namespace std;
31 using namespace libconfig;
32 
33 // This example reads complex types from config file using method chains.
34 
example2(Config & cfg)35 void example2(Config& cfg)
36 {
37 	ChainedSetting cs(cfg.getRoot());
38 
39 	auto books = cs["inventory"]["books"];
40 	if (!books.exists())
41 	{
42 		cerr << "No book section available." << endl;
43 		return;
44 	}
45 
46 	cout << setw(30) << left << "TITLE" << "  "
47 			<< setw(30) << left << "AUTHOR" << "   "
48 			<< setw(6) << left << "PRICE" << "  "
49 			<< "QTY"
50 			<< endl;
51 
52 	const int count = books.getLength();
53 	for(int i = 0; i < count; ++i)
54 	{
55 		auto book = books[i];
56 
57 		string title = book["title"];
58 		string author = book["author"];
59 		double price = book["price"].min(0.0);
60 		int qty = book["qty"].min(0);
61 
62 		// Only output the record if all of the expected fields are present.
63 		if(book.isAnySettingMissing()) continue;
64 
65 		cout << setw(30) << left << title << "  "
66 			<< setw(30) << left << author << "  "
67 			<< '$' << setw(6) << right << price << "  "
68 			<< qty
69 			<< endl;
70 	}
71 }
72