问题描述
假设我想计算用户输入的一系列数字的二进制值,但是我不想设置用户可以输入的数字的限制,所以我在Python 3中这样做:
try:
lst = list()
while True:
n = int(input("Enter the number: "))
b = binary_of(n) // Function to find binary value
lst.append(b)
except:
print("The respective binary values are",'\n')
print(lst)
在上面的代码中,当用户输入非整数值并且程序移至“ except”以打印列表时,“ try”停止执行。这正是我想要的。
我可以在C ++中做类似的事情吗?也有C ++的“尝试与例外”版本吗?
解决方法
exception
是程序执行期间出现的问题。允许用户停止提供更多输入不是问题。您的逻辑应该处理。有多种方法可以实现。
Try..catch
永远在您身边。
一种方法可能是解析输入以检查输入是否为int。如果不是,请break
while
。
另一种方法可能如下所示。
#include <iostream>
using namespace std;
int main() {
int num;
cin >> num;
while(cin.fail()){
//your logic goes here
cin.clear();
cin.ignore(numeric_limits<int>::max(),'\n');
cin >> num;
};
return 0;
}