Daniel Petti | b6c885b | 2014-09-12 10:04:28 -0700 | [diff] [blame^] | 1 | #ifndef AOS_COMMON_UTIL_STRING_TO_NUM_H_ |
| 2 | #define AOS_COMMON_UTIL_STRING_TO_NUM_H_ |
| 3 | |
| 4 | #include <sstream> |
| 5 | #include <string> |
| 6 | |
| 7 | namespace aos { |
| 8 | namespace util { |
| 9 | |
| 10 | // Converts a string into a specified integral type. If it can't be converted |
| 11 | // completely or at all, or if the converted number would overflow the |
| 12 | // specified integral type, it returns false. |
| 13 | template<typename T> |
| 14 | inline bool StringToInteger(const ::std::string &input, T *out_num) { |
| 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 |