有没有办法让异常无限期地工作?

时间:2020-06-27 08:00:42

标签: c++ exception c++17

我一直在尝试从用户那里获取输入。我想确保输入内容符合我使用try and catch块的其余代码的要求。

但是,仅捕获一次后,它将中止代码。我想确保在捕获错误之后,它实际上会返回输入函数多次,直到用户为程序提供有效输入为止。除了完全不使用try catch块之外,有没有办法做到这一点?

这是代码:

#include <iostream>
#include <string>
#include <typeinfo>

using namespace std;

long num; // I need num as global

long get_input()
{
    string input;
    long number;

    cout << "Enter a positive natural number: ";
    cin >> input;

    if ( !(stol(input)) ) // function for string to long conversion
        throw 'R';

    number = stol(input);

    if (number <= 0)
        throw 'I';

    return number;
}

int main()
{
    try
    {
        num = get_input();
    }
    catch (char)
    {
        cout << "Enter a POSTIVE NATURAL NUMBER!\n";
    }

// I want that after catch block is executed, the user gets chances to input the correct number 
// until they give the right input.

    return 0;
}

1 个答案:

答案 0 :(得分:1)

您需要明确编写这样的处理方式,例如通过循环:

int main()
{
    while (1) {
        try
        {
            num = get_input();
            return 0; // this one finishes the program
        }
        catch (char)
        {
            cout << "Enter a POSTIVE NATURAL NUMBER!\n";
        }
    }
}