fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <sstream>
  4.  
  5. double ask_for_number(std::string const &prompt)
  6. {
  7. double x;
  8. std::string line;
  9. while((std::cout << prompt << ": ") //prompt for input
  10. && std::getline(std::cin, line) //read whole line (almost never fails)
  11. && !(std::istringstream{line} >> x)) //validate input
  12. {
  13. std::cout << "Invalid input, please try again." << std::endl;
  14. }
  15. return x;
  16. }
  17.  
  18. int main()
  19. {
  20. int n1 = ask_for_number("Enter a number");
  21. int n2 = ask_for_number("Enter another number");
  22.  
  23. std::cout << "n1 + n1 = " << n1 + n2 << std::endl;
  24. }
  25.  
Success #stdin #stdout 0s 3280KB
stdin
7
3
stdout
Enter a number: Enter another number: n1 + n1 = 10