I've this example:
int main() {
int val{};
bool stop = false;
char c;
while (!stop) {
std::cout << "val: ";
try {
if (!(std::cin >> val)) {
throw std::runtime_error("bad input");
}
std::cout << val << " : " << val * val << std::endl;
}
catch (std::exception& e) {
std::cout << e.what() << std::endl;
std::cin.clear();
std::cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
std::cout << "retry\?\n>>" << std::endl;
std::cin >> c;
if (c != 'y' && c != 'Y')
stop = true;
}
}
}
The code works fine but I want to know should I use this in a real world program? Because I've seen some alternatives: getting the input as a string then using conversion to integral types.
- My question: is Should I use exception handling for invalid input like characters where it should be integers.. or Just sue string and conversion?