简体   繁体   English

尝试不捕获非整数输入

[英]try is not catching a non-integer input

What I want to achieve is simple, if the input is not an integer it should display "Number is invalid". 我要实现的方法很简单,如果输入的不是整数,则应显示“ Number in invalid”。

Number is already set to be an integer ( int number ). Number已设置为整数( int number )。

#include <iostream>

using namespace std;

int main(){
    int number;
    try{
        cin >> number;
    }catch(const ios::failure &){
        cout << "Number is invalid";
    }
}

Result for input -> 1 is => 1 and result for input -> a is => a, so it is not catching anything. 输入-> 1的结果为=> 1,输入-> a的结果为=> a,因此它不会捕获任何内容。

What am I missing in this try-catch block? 在try-catch块中我缺少什么?

You have to enable exceptions. 您必须启用例外。 Add cin.exceptions(istream::failbit); 添加cin.exceptions(istream::failbit); before the call to cin . 在致电cin之前。 iostreams by default do not use exceptions (they were originally designed at a time when exceptions were not even part of C++). iostream默认情况下不使用异常(它们最初是在异常甚至不属于C ++的时候设计的)。

Streams do not throw exceptions by default. 默认情况下,流不会引发异常。 If you want them to throw exceptions you need to enable them by calling the exceptions() member function. 如果希望它们引发异常,则需要通过调用exceptions()成员函数来启用它们。

std::cin.exceptions(std::istream::failbit);

Don't enable exceptions in streams unless you really need them and understand what they do. 不要在流中启用异常,除非您确实需要它们并了解它们的作用。 Most input failures should be handled by prompting and repeating, not by throwing exceptions. 大多数输入失败应通过提示和重复来处理,而不是引发异常。 After repeated failures, sure, throw an exception. 在反复失败之后,请确保抛出异常。 But that's not the stream's responsibility. 但这不是流的责任。

However, if you do need to throw an exception on an input failure, it's easy to do: 但是,如果确实需要在输入失败时引发异常,则很容易做到:

try {
    std::cin >> number;
    if (!std::cin)
        throw whatever;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM