fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4.  
  5. template <typename T>
  6. bool toNumber(const std::string &str, T& num)
  7. {
  8. std::istringstream ss(str);
  9. return static_cast<bool>(ss >> num);
  10. // or:
  11. // return !!(ss >> num);
  12. }
  13.  
  14. int main()
  15. {
  16. int x, y;
  17.  
  18. if (toNumber("90", x))
  19. std::cout << x << std::endl;
  20. else
  21. std::cout << "Not a number" << std::endl;
  22.  
  23. if (toNumber("New York", y))
  24. std::cout << y << std::endl;
  25. else
  26. std::cout << "Not a number" << std::endl;
  27.  
  28. return 0;
  29. }
Success #stdin #stdout 0.01s 5516KB
stdin
Standard input is empty
stdout
90
Not a number