fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <cctype>
  4. #include <ios>
  5.  
  6. bool isNumber(std::string const &str)
  7. {
  8. bool isNegative = (str[0] == '-');
  9. bool metDecimalDot = false;
  10. return std::all_of(str.cbegin() + isNegative, str.cend(), [&](char ch) {
  11. return isdigit(ch) || (!metDecimalDot && (metDecimalDot = (ch == '.')));
  12. });
  13. }
  14.  
  15. int main() {
  16. std::string input;
  17. while (std::cin >> input) {
  18. std::cout << std::boolalpha << "Is '" << input << "' a number? " << isNumber(input) << "\n";
  19. }
  20. return 0;
  21. }
Success #stdin #stdout 0s 3460KB
stdin
1
42
3.00
3.14
3.1400
3.14.15
adsf
@
.
stdout
Is '1' a number? true
Is '42' a number? true
Is '3.00' a number? true
Is '3.14' a number? true
Is '3.1400' a number? true
Is '3.14.15' a number? false
Is 'adsf' a number? false
Is '@' a number? false
Is '.' a number? true