我正在编写一个打开文件的功能,其中打开模式取决于用户的选择。下面给出的是函数

void open_file(char T)
{
    string name;
open:
    cout << "\n Enter filename/path : ";
    cin >> name;
    if(T == 'N')
        file.open(name);
    else
        if(T == 'O')
        {
            file.open(name, ios::app | ios::in);
            if(!file)
            {
                cout << "\n File not found. Try again";
                goto open;
            }
            file.seekg(0);
        }
}

如果找不到该文件,则程序转到open:,因为我使用了未理解的goto语句。请注意,open:name声明之后开始。

我想知道goto open是否比open_file('O')的内存效率低/慢,因为每次调用open_file('O')都会声明name
请注意:人们不使用goto语句的唯一原因是他们使程序更加复杂。

最佳答案

如果您使用while块而不是goto,则将更易于阅读。无需递归。

void open_file(char T)
{
    string name;
    bool retry;
    do {
        retry = false;
        cout << "\n Enter filename/path : ";
        cin >> name;
        if(T == 'N')
            file.open(name);
        else
            if(T == 'O')
            {
                file.open(name, ios::app | ios::in);
                if(!file)
                {
                    cout << "\n File not found. Try again";
                    retry = true;
                }
                else
                    file.seekg(0);
            }
    } while (retry);
}

09-30 18:35
查看更多