John Park | 33858a3 | 2018-09-28 23:05:48 -0700 | [diff] [blame^] | 1 | #ifndef AOS_UTIL_STRING_TO_NUM_H_ |
| 2 | #define AOS_UTIL_STRING_TO_NUM_H_ |
Daniel Petti | b6c885b | 2014-09-12 10:04:28 -0700 | [diff] [blame] | 3 | |
| 4 | #include <sstream> |
| 5 | #include <string> |
| 6 | |
| 7 | namespace aos { |
| 8 | namespace util { |
| 9 | |
Daniel Petti | 5aa2979 | 2014-12-27 17:48:07 -0500 | [diff] [blame] | 10 | // Converts a string into a specified numeric type. If it can't be converted |
Daniel Petti | b6c885b | 2014-09-12 10:04:28 -0700 | [diff] [blame] | 11 | // completely or at all, or if the converted number would overflow the |
Daniel Petti | 5aa2979 | 2014-12-27 17:48:07 -0500 | [diff] [blame] | 12 | // specified type, it returns false. |
Daniel Petti | b6c885b | 2014-09-12 10:04:28 -0700 | [diff] [blame] | 13 | template<typename T> |
Daniel Petti | 5aa2979 | 2014-12-27 17:48:07 -0500 | [diff] [blame] | 14 | inline bool StringToNumber(const ::std::string &input, T *out_num) { |
Daniel Petti | b6c885b | 2014-09-12 10:04:28 -0700 | [diff] [blame] | 15 | ::std::istringstream stream(input); |
| 16 | stream >> *out_num; |
| 17 | |
| 18 | if (stream.fail() || !stream.eof()) { |
| 19 | return false; |
| 20 | } |
| 21 | |
| 22 | return true; |
| 23 | } |
| 24 | |
| 25 | |
| 26 | } // util |
| 27 | } // aos |
| 28 | |
| 29 | #endif |