fork download
  1. #include <iostream>
  2. #include <array>
  3. #include <limits>
  4. #include <iterator>
  5. #include <algorithm>
  6.  
  7. template<typename T, typename Q, typename E>
  8. T askForOne(std::ostream & out, std::istream & in, Q&& question, E&& error) {
  9. T value;
  10. out << question;
  11. while (not (in >> value)) {
  12. in.clear();
  13. in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  14. out << error;
  15. }
  16. return value;
  17. }
  18.  
  19.  
  20. template<typename T, std::size_t N, typename Q, typename E>
  21. std::array<T, N> askFor(std::ostream & out, std::istream & in, Q&& question, E&& error) {
  22. std::array<T, N> values;
  23. auto const scan = [&in, &values] {
  24. for (auto & value : values) {
  25. if (not (in >> value)) {
  26. return false;
  27. }
  28. }
  29. return true;
  30. };
  31. out << question;
  32. while (not scan()) {
  33. in.clear();
  34. in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  35. out << error;
  36. }
  37. return values;
  38. }
  39.  
  40.  
  41. int main(int, char **) {
  42. using namespace std;
  43. int one = askForOne<int>(cout, cin, "Int? ", "Meh. ");
  44. int two = askForOne<int>(cout, cin, "Int? ", "Meh. ");
  45. auto ints = askFor<int, 5>(cout, cin, "5 ints? ", "Meh. ");
  46. cout << "one = " << one << endl;
  47. cout << "two = " << two << endl;
  48. cout << "ints = ";
  49. copy(begin(ints), end(ints), ostream_iterator<int>{cout, ", "});
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 3416KB
stdin
Haha
21
Ha ha ha
Ha
42
1 2 3 4 BUUUUUU
1 2 3 4 BUU JA
Ehm 1 2 3 4 5
9 8 7 6 5
stdout
Int? Meh. Int? Meh. Meh. 5 ints? Meh. Meh. Meh. one = 21
two = 42
ints = 9, 8, 7, 6, 5,