2015-11-22 109 views
0

我正在写一个函数,打开一个文件,其中打开模式取决于用户的选择。下面给出的函数goto语句vs递归

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声明。请注意0​​在申报name后开始。

我想知道,如果goto open是更少的内存效率/比open_file('O')或不慢,因为open_file('O')将在每次调用时声明name。 请注意:人们给予不使用goto陈述的唯一原因是他们使程序更复杂。

回答

2

如果您使用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); 
} 
+0

你的意思是'while(file){// ...}'? –

+0

你没有在你的问题中定义文件,所以我定义了一个布尔值来检查打开是否成功。 – Shloim

+0

不错,但它是一个fstream类的成员函数。无论如何,非常感谢! –