如何捕获无效的用户输入 [英] How to catch invalid user inputs
问题描述
我不理解Try,throw,catch语句,并且想知道当代码中的所有int应该为int时,为什么最好捕获一个char.这是为了防止人们愚蠢到当我要求他们最喜欢的电话号码时加一个"a".这是我尝试保护我的代码的示例,以防止有人在输入整数时输入字符:
I am not understanding Try, throw, catch statements and am wondering how would be the best why to catch a char when all in puts in your code should be int. It is to help stop people form being silly and putting an "a" when I ask for their favorite number. Here is an example of my code i am trying to protect from someone entering a char when i want ints:
int a, b;
std::cout << "Enter a Numerator: ";
std::cin >> a;
std::cout << "Enter a Denominator: ";
std::cin >> b;
推荐答案
如果您合并了两个问题的两个答案(此),我在您的问题的评论部分中提到过,您会得到的,
If you merge the two answers from the two questions (this and this), I referred to in the comments section of your question, you would get this,
#include <iostream>
int main()
{
int a, b;
std::cout << "Enter a Numerator: ";
std::cin >> a;
std::cout << "Enter a Denominator: ";
std::cin >> b;
if (!std::cin.good())
{
throw std::invalid_argument( "received strings. Need integers" );
}
}
如第一个链接的答案所述,您可以在此处进行引用.有关抛出什么异常的更多信息.
As the first linked answer mentions, you can refer here for more on what exceptions to throw.
并且如第二个链接的答案所述,如果用户未输入期望的正确数据类型,"cin将切换它的故障位.将输入的数据类型更改为int并检查此故障位将使您验证用户输入." .
And as the second linked answer mentions, "cin will toggle it's failbit if the user does not enter a correct data type that it was expecting. Changing the datatype of the inputs to ints and checking this failbit will allow you to validate user input." .
事后想到,最好也将分母检查为零,并在上面的代码示例中添加类似的内容.
Just as an after thought, you better check that denominator for zero also, with something like this added to the above code example.
if (b /*assuming b is denominator*/ == 0) {
throw std::overflow_error("Divide by zero exception");
}
这篇关于如何捕获无效的用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!