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
89
90
91
92
|
#ifndef UTIL_H
#define UTIL_H
#include <algorithm>
#include <cstring>
#include <stdexcept>
#include <string>
namespace util
{
/* TODO */
constexpr char SPACE[] = " ";
constexpr char COLON[] = ":";
constexpr char SEMICOLON[] = ";";
inline void trim(std::string& str)
{
str.erase(str.begin(), std::find_if_not(str.cbegin(), str.cend(), ::isspace));
str.erase(std::find_if_not(str.crbegin(), str.crend(), ::isspace).base(), str.end());
}
template<const char* delim, typename Accumulate>
void accumulate(const std::string& str, Accumulate acc)
{
size_t pos{};
std::string elem;
while ((pos = str.find(delim)) != std::string::npos) {
auto sub = str.substr(0, pos);
trim(sub);
acc(sub);
pos += std::strlen(delim);
}
}
/* ---- */
/** @brief Discard element from stream by type.
*
* @tparam T the type of the element to discard.
* @param stream the input stream.
*
* @return the input stream.
*/
template<typename T, typename CharT, typename Traits>
std::basic_istream<CharT, Traits>& skip(std::basic_istream<CharT, Traits>& stream)
{
T discard;
return stream >> discard;
}
/** @brief Skip token in stream.
*
* @tparam keyword the token to skip.
* @param stream the input stream.
*
* @return the input stream.
*
* @note The token needs to be declared as a `const char[]`, but normally,
* string literals are `const char*`.
*
* ```cpp
* constexpr char RESULT[] = "Result:";
*
* int main(int argc, char* argv[])
* {
* int res;
* std::istringstream in{ "Result: 42"}
* in >> skip<RESULT> >> res;
*
* // ...
*
* return 0
* }
* ```
*/
template<const char* keyword, typename CharT, typename Traits>
std::basic_istream<CharT, Traits>& skip(std::basic_istream<CharT, Traits>& stream)
{
std::string word;
stream >> word;
if (word != keyword)
{
throw std::invalid_argument("Malformed input");
}
return stream;
}
} // namespace util
#endif //UTIL_H
|