Try和catch语句对于实际异常很容易,但是如何为自我强制限制编写try / catch?
例如,如果我从cin得到一个整数,我想要2,4或7,以及其他任何打印“那个数字无效”并再试一次,这将如何用c ++编写?
Try and catch statements are easy for actual exceptions, but how might I write a try/catch for a self-imposed restriction?
For example, if I am getting an integer from cin that I want to be either 2,4, or 7, and anything else to print "That number is not valid" and try again, how would this get written in c++?
最满意答案
@Adam Rosenfield是对的:异常应保留用于特殊情况 - 即,您不希望发生的事情(或至少不经常发生)。 预计会经常发生输入错误数据的用户。
由于您总是希望至少读取一次输入,因此这是do / while循环有意义的情况:
do { std::cin >> number; } while (number != 2 && number != 4 && number != 7);@Adam Rosenfield is right: exceptions should be reserved for exceptional situations -- i.e., things you don't expect to happen (or at least not very often). A user entering bad data is expected to happen -- frequently.
Since you always want to read the input at least once, this is a situation where a do/while loop makes sense:
do { std::cin >> number; } while (number != 2 && number != 4 && number != 7);更多推荐
发布评论