簡體   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