Line | |
---|
1 | #ifndef _String2Number_H__ |
---|
2 | #define _String2Number_H__ |
---|
3 | |
---|
4 | #include <string> |
---|
5 | #include <sstream> |
---|
6 | #include <iostream> |
---|
7 | |
---|
8 | #include "core/Debug.h" |
---|
9 | #include "UtilPrereqs.h" |
---|
10 | |
---|
11 | /** |
---|
12 | * String to number conversion |
---|
13 | * |
---|
14 | * This class converts a number inside a std::string |
---|
15 | * into a numeric type number (int,float,double) |
---|
16 | * Number in string can be decimal, hexadecimal or octal |
---|
17 | * |
---|
18 | * @author Nicolas Perrenoud<nicolape@ee.ethz.ch> |
---|
19 | * |
---|
20 | * @example |
---|
21 | * float f; |
---|
22 | * String2Number<float>(f, std::string(" 123.45 ")); |
---|
23 | */ |
---|
24 | |
---|
25 | template <class T> |
---|
26 | class String2Number |
---|
27 | { |
---|
28 | private: |
---|
29 | bool success_; |
---|
30 | |
---|
31 | public: |
---|
32 | /** |
---|
33 | * Constructor |
---|
34 | * |
---|
35 | * First value is the target variable, the second vector is the |
---|
36 | * string where the number is taken from, the third parameter |
---|
37 | * should be one of std::hex, std::dec or std::oct (dec is default value) |
---|
38 | */ |
---|
39 | inline String2Number(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&) = std::dec, int haltOnError=1) |
---|
40 | { |
---|
41 | std::istringstream iss(s); |
---|
42 | success_ = !(iss >> f >> t).fail(); |
---|
43 | |
---|
44 | if (!success_ && haltOnError==1) |
---|
45 | { |
---|
46 | COUT(1) << "Error: Conversion from string to number in \"" << s << "\" failed." << std::endl; |
---|
47 | exit(1); |
---|
48 | } |
---|
49 | } |
---|
50 | }; |
---|
51 | |
---|
52 | #endif /* _String2Number_H__ */ |
---|
Note: See
TracBrowser
for help on using the repository browser.