返回函数开头的方法

Ale*_*lex 0 c++

在函数调用之后,C++是否有任何类型的实用程序可以返回函数的开头?例如,在calculate函数中调用help().

void help()
{
     cout << "Welcome to this annoying calculator program.\n";
     cout << "You can add(+), subtract(-), multiply(*), divide(/),\n";
     cout << "find the remainder(%), square root(sqrt()), use exponents(pow(x,x)),\n";
     cout << "use parentheses, assign variables (ex: let x = 3), and assign\n";
     cout << " constants (ex: const pi = 3.14). Happy Calculating!\n";
     return;
}

void clean_up_mess()        // purge error tokens
{
    ts.ignore(print);
}

const string prompt = "> ";
const string result = "= ";

void calculate()
{
    while(true) try {
        cout << prompt;
        Token t = ts.get();
        if (t.kind == help_user) help();  
        else if (t.kind == quit) return;
        while (t.kind == print) t=ts.get();
        ts.unget(t);
        cout << result << statement() << endl;
    }
    catch(runtime_error& e) {
        cerr << e.what() << endl;
        clean_up_mess();
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然技术上我的帮助功能的实现工作正常,但它并不完美.在调用help之后,返回,继续尝试cout << result << statement()<< endl; 这是不可能的,因为没有输入任何值.因此,它给出了一个小错误消息(程序中的其他地方),然后继续该程序.没有功能问题,但它很难看,我不喜欢它(:P).

那么有什么方法可以帮助函数返回,返回到计算的开始并重新开始?(我在if(t.kind == help_user)块中插入一个函数调用来调用calculate,但是我认为这只会延迟问题而不是解决问题.)

Emi*_*l H 5

这可能是你想要的?

if (t.kind == help_user) {
    help();  
    continue;
}
Run Code Online (Sandbox Code Playgroud)


GMa*_*ckG 5

你可以使用goto,但是当你这样做时,请考虑自己.它被认为是不好的做法,它的良好用途是罕见的,相距甚远.

我想你正在寻找的是继续:

void do_calculate(void)
{
    while (true)
    {
        cout << prompt;
        Token t = ts.get();

        if (t.kind == help_user)
        {
            help();  
            continue; // <- here
        }
        else if (t.kind == quit)
        {
            return;
        }

        while (t.kind == print)
        {
            t = ts.get();
        }
        ts.unget(t);

        cout << result << statement() << endl;
    }
}

void calculate()
{
    try
    {
        do_calculate();
    }
    catch (const std::exception& e)
    {
        cerr << e.what() << endl;
        clean_up_mess();
    }
}
Run Code Online (Sandbox Code Playgroud)

我还重新格式化了你的代码.我认为这对每个人来说都更具可读性,但只是想让你比较一下.

  • try/catch子句现在不再干扰计算功能.

  • 'if'语句使用括号来保持一致性.此外,它更容易阅读,因为我知道控制是否在这些括号内.

  • catch将捕获std :: exception,而不是runtime_error.所有标准异常都继承自std :: exception,所以通过捕获它你知道你可以捕获任何东西.