fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <stdexcept>
  4. #include <limits>
  5. using namespace std;
  6.  
  7. int main() {
  8. int num = 0;
  9. string s;
  10. size_t pos;
  11.  
  12. while (true){
  13. cout << "enter num: ";
  14. if (!(cin >> s)){
  15. cin.clear();
  16. cin.ignore(numeric_limits<streamsize>::max(), '\n');
  17. cout << "input error, try again" << endl;
  18. }
  19. else{
  20. try{
  21. num = stoi(s, &pos);
  22. if (pos != s.size()) throw invalid_argument("");
  23. if (num > 0){
  24. break;
  25. }
  26. cout << "num must be greater than 0" << endl;
  27. }
  28. catch (const exception &){
  29. cout << "num must be an int" << endl;
  30. }
  31. }
  32. }
  33.  
  34. cout << num;
  35. return 0;
  36. }
Success #stdin #stdout 0.01s 5328KB
stdin
0 0 a 1.0 1
stdout
enter num: num must be greater than 0
enter num: num must be greater than 0
enter num: num must be an int
enter num: num must be an int
enter num: 1