ATLAS Offline Software
Loading...
Searching...
No Matches
StringParse.h
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2023 CERN for the benefit of the ATLAS collaboration
3*/
4
5#ifndef CXXUTILS_STRINGPARSE_H
6#define CXXUTILS_STRINGPARSE_H
7#include <string>
8#include <vector>
9#include <sstream>
10#include <charconv>
11#include <iostream>
12#include <iomanip>
13
33class StringParse: public std::vector<std::string> {
34public:
35
37 StringParse(const std::string& input) {
38 std::istringstream instring(input);
39 std::string token;
40 while (instring >> token) this->push_back(token);
41 }
42
44 template <typename T> T piece(size_t num) const {
45 if (num > this->size()) return {-1};
46 std::string token = this->at(num-1);
47 T result{-1};
49 auto [ptr, ec] = std::from_chars(token.data(), token.data() + token.size(), result);
50 if (ec == std::errc() && ptr == token.data() + token.size()) return result;
51 if (ec == std::errc::invalid_argument || ptr != token.data() + token.size() ) return {-1}; //std::cout << "This number cannot be parsed.\n";
52 if (ec == std::errc::result_out_of_range) return {-1}; //std::cout << "This number is out of range of the return type.\n";
53 return {-1};
54 }
55};
56
57template <> std::string StringParse::piece(size_t num) const {
58 return num > this->size() ? std::string{} : this->at(num-1);
59}
60#endif
T piece(size_t num) const
Templated function to get the num'th token as any numeric type.
Definition StringParse.h:44
StringParse(const std::string &input)
Constructor, taking a string of whitespace-separated tokens.
Definition StringParse.h:37