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