对不需要的整数进行自我强制尝试/捕获(Self

编程入门 行业动态 更新时间:2024-10-24 20:16:00
对不需要的整数进行自我强制尝试/捕获(Self-imposed try/catch for unwanted integers)

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);

更多推荐

本文发布于:2023-07-07 21:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1068550.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   对不   进行自我

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!