fork download
  1. #include <iostream>
  2. #include <limits>
  3.  
  4. template <typename T>
  5. T validated_input(std::string error_message)
  6. {
  7. T value;
  8. while(not (std::cin >> value)) { //While input fails
  9. std::cout << error_message; //Output error message
  10. std::cin.clear(); //clear error state
  11. std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //ignore errorneous input
  12. }
  13. return value;
  14. }
  15.  
  16.  
  17. int main() {
  18. std::cout << "Enter your weight in pounds to one decimal point: ";
  19. double weight = validated_input<double>("Enter floating point value!\n");
  20. }
Success #stdin #stdout 0s 3476KB
stdin
Hello!
3.14
stdout
Enter your weight in pounds to one decimal point: Enter floating point value!