Loading...
Searching...
No Matches
StringHelpers.cc
Go to the documentation of this file.
2
3#include <cassert>
4#include <iostream>
5#include <type_traits>
6
7using namespace std::string_literals;
8
9namespace eonc::helpers {
10template <typename T>
11std::vector<T> get_val_from_string(std::string_view line,
12 std::optional<size_t> nelements) {
13 assert(not line.empty());
14 std::vector<T> retval;
15 const bool b_isunsigned{std::is_unsigned<T>::value};
16 auto elements{get_split_strings(line)};
17 if (nelements.has_value()) {
18 // Used to truncate if the number of elements is given
19 assert(nelements > 0);
20 elements.resize(nelements.value());
21 }
22 // If it is unsigned then use long double else T
23 for (typename std::conditional<b_isunsigned, long double, T>::type tmp;
24 auto elem : elements) {
25 if (not isNumber(elem)) {
26 continue;
27 }
28 std::istringstream ss{
29 elem}; // instead of {ss.str(elem); ss >> tmp; ss.clear();}
30 ss >> tmp;
31 if (b_isunsigned and tmp < 0) {
32 std::cerr
33 << "Can't represent negative numbers with an unsigned type, bailing on "s
34 << tmp << "\n";
35 assert(tmp > 0);
36 }
37 retval.push_back(tmp);
38 }
39 return retval;
40}
41// Instantiate explicitly
42// This is useful since we don't want to support other types either
43template std::vector<size_t> get_val_from_string(std::string_view,
44 std::optional<size_t>);
45template std::vector<double> get_val_from_string(std::string_view,
46 std::optional<size_t>);
47
48std::vector<std::string> get_split_strings(std::string_view line) {
49 std::istringstream ss{std::string{line}};
50 std::vector<std::string> split_strings{std::istream_iterator<std::string>{ss},
51 std::istream_iterator<std::string>()};
52 return split_strings;
53}
54
55bool isNumber(std::string_view token) {
56 return std::regex_match(
57 std::string{token},
58 std::regex(("((\\+|-)?[[:digit:]]+)(\\.(([[:digit:]]+)?))?")));
59}
60} // namespace eonc::helpers
bool isNumber(std::string_view token)
Figure out if a string has a number in it.
std::vector< std::string > get_split_strings(std::string_view line)
Split a string into constituent strings.
std::vector< T > get_val_from_string(std::string_view line, std::optional< size_t > nelements)
Parse a string into values.