This is a tiny learning program that lead to an interesting question: how can I best/most elegantly handle user entered numbers? This method works, fails cleanly, and reads well. It doesn't apply to types other than build in ones (as far as I know), but for floats and integers it's a nice feature. But it doesn't scale well, and seems cumbersome. Thoughts?
Read two numbers (a,b) then increment (a) by one if ( a > b ) and (a > 0) otherwise decrement (a) by one. Print (a).
Sample Input:
27
36Sample Output:
26
#include <iostream> #include <stdexcept> int main() { int a, b; try { std::cin >> a; if (std::cin.fail()) throw std::runtime_error("Input is not an integer\n"); std::cin >> b; if (std::cin.fail()) throw std::runtime_error("Input is not an integer\n"); } catch (const std::runtime_error& e) { std::cout << e.what(); return 1; } if (a > b && a > 0) { ++a; } else { --a; } std::cout << a; return 0; }