繁体   English   中英

如何在C ++中引发std :: iostream故障?

[英]How to throw an std::iostream failure in C++?

如何手动引发std :: iostream :: failure? 我有一个try-catch循环,当用户尝试输入非整数字符串时会捕获异常,但是如果用户尝试输入浮点数,则不会引发异常,因为它将尝试读取小数点前的所有内容浮点值。 我的解决方案是如果流中仍有剩余数据,则手动引发异常,该怎么办?

/*
Sample Implementation Code in C++
Handling Inputs from User in C++
This code only stops running when the user
inputs the appropriate values. Otherwise, the program
will continue asking the user for input.
*/

#include <iostream>
#include <limits> //numeric_limits
#include <stdexcept>

int main() {
    std::cin.exceptions(std::ios::failbit); // set exceptions to be thrown when a failbit is set
    int num = 0;
    int den = 0;

    while (true) {
        try {
            std::cout << "Enter numerator: ";
            std::cin >> num;
            if(std::cin.peek() != '\n') {
                //HOW TO DO THIS PART?
                std::iostream::failure e;
                throw e;
            }
            std::cout << "Enter denominator: ";
            std::cin >> den;
            std::cout << "The quotient is " << num/den << std::endl;
        } catch (std::iostream::failure& e){
            std::cout << "Input should be an integer." << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    return 0;
}

显然,它很简单:

throw std::iostream::failure("");

我忘记的重要一点是空字符串(“”),因为它有一个接受字符串参数而不是void参数的构造函数。

暂无
暂无

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

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