flexiblesusy is hosted by Hepforge, IPPP Durham
FlexibleSUSY
string_conversion.cpp
Go to the documentation of this file.
1// ====================================================================
2// This file is part of FlexibleSUSY.
3//
4// FlexibleSUSY is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published
6// by the Free Software Foundation, either version 3 of the License,
7// or (at your option) any later version.
8//
9// FlexibleSUSY is distributed in the hope that it will be useful, but
10// WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12// General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with FlexibleSUSY. If not, see
16// <http://www.gnu.org/licenses/>.
17// ====================================================================
18
19#include "string_conversion.hpp"
20#include "error.hpp"
21#include <cerrno>
22#include <climits>
23#include <cstdlib>
24
25namespace flexiblesusy {
26
27int to_int(const char* s)
28{
29 char* end = nullptr;
30 errno = 0;
31
32 const long l = std::strtol(s, &end, 10);
33
34 if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX) {
35 errno = 0;
36 throw ReadError("range overflow occurred in conversion to int");
37 }
38 if ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN) {
39 errno = 0;
40 throw ReadError("range underflow occurred in conversion to int");
41 }
42 if (*s == '\0' || *end != '\0') {
43 errno = 0;
44 throw ReadError("cannot convert string to int");
45 }
46
47 errno = 0;
48
49 return static_cast<int>(l);
50}
51
52
53long to_long(const char* s)
54{
55 char* end = nullptr;
56 errno = 0;
57
58 const long l = std::strtol(s, &end, 10);
59
60 if (errno == ERANGE && l == LONG_MAX) {
61 errno = 0;
62 throw ReadError("range overflow occurred in conversion to long");
63 }
64 if (errno == ERANGE && l == LONG_MIN) {
65 errno = 0;
66 throw ReadError("range underflow occurred in conversion to long");
67 }
68 if (*s == '\0' || *end != '\0') {
69 errno = 0;
70 throw ReadError("cannot convert string to long");
71 }
72
73 errno = 0;
74
75 return l;
76}
77
78
79double to_double(const char* s)
80{
81 char* end = nullptr;
82 errno = 0;
83
84 const double d = std::strtod(s, &end);
85
86 if (errno == ERANGE) {
87 errno = 0;
88 throw ReadError("range error occurred in conversion to double");
89 }
90 if (*s == '\0' || *end != '\0') {
91 errno = 0;
92 throw ReadError("cannot convert string to double");
93 }
94
95 errno = 0;
96
97 return d;
98}
99
100} // namespace flexiblesusy
double * end(GSL_vector &v)
iterator to end of GSL_vector
Definition: gsl_vector.cpp:254
double to_double(const char *s)
long to_long(const char *s)
int to_int(const char *s)