-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.cpp
88 lines (81 loc) · 1.95 KB
/
library.cpp
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include "library.h"
#include <algorithm>
#include <fstream>
// Functions to read from the command line string parameters
///////
char* getCmdOption(char ** begin, char ** end, const std::string & option)
{
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end)
{
return *itr;
}
return 0;
}
///////
bool cmdOptionExists(char** begin, char** end, const std::string& option)
{
return std::find(begin, end, option) != end;
}
///////////
//// Assisting functions for configuration loading
//function to read files
std::string readfile(std::string filename) {
std::string filecontents = "";
std::string line;
std::ifstream fin;
if (fin.is_open()) {
fin.close();
}
try {
fin.open(filename);
}
catch (const std::exception & ex) {
std::cerr << ex.what() << std::endl;
throw;
}
if (fin.bad()) {
std::string err_msg = "the file " + filename + " was not created";
std::cerr << err_msg << std::endl;
throw std::runtime_error{ err_msg };
}
if (!fin.is_open()) {
std::string err_msg = "the file " + filename + " was not opened";
std::cerr << err_msg << std::endl;
throw std::runtime_error{ err_msg };
}
else {
while (getline(fin, line)){
filecontents = filecontents + line;
}
fin.close();
}
return filecontents;
}
// function to parse json objects
json parse_json_string(std::string inputjsonstring) {
std::stringstream ss;
ss << inputjsonstring;
json j = json::parse(ss);
//another way to do it is to use inputjsonstring.c_str()
return j;
}
// function to split string
std::vector<std::string> split(const std::string& str, const std::string& delim)
{
std::vector<std::string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == std::string::npos){
pos = str.length();
}
std::string token = str.substr(prev, pos - prev);
if (!token.empty()) {
tokens.push_back(token);
}
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
return tokens;
}