2014-10-17 319 views
0

我需要這樣做:打開用戶指定的文件進行輸入。提示文件的名稱,將其讀入一個字符串變量,echo將其打印到終端,然後打開它。如果文件未成功打開,進入一個打印出錯信息的循環,重置輸入文件流變量(Input_file_stream_var.clear();其中Input_file_stream_var是輸入文件流變量的名稱),獲取新文件名並嘗試打開新文件。循環繼續,直到用戶成功輸入有效的文件名或按ctrl-c退出。爲什麼這個循環不循環?

這裏是我到目前爲止的代碼,但我不能讓它回到過程中,如果文件沒有打開。

#include <iostream> 
#include <fstream> 
#include <string> 
#include <sstream> 
#include <iomanip> 
using namespace std; 

int main() 
{ 
    // Variables 
    char test; 
    string infname, outfname; 
    fstream infile, outfile; 
    do 
    { 
     // Propt for and echo print input file 
     cout << endl << "Enter the name of the input file: "; 
     cin >> infname; 
     cout << infname << endl; 

     infile.open(infname.c_str()); 

     // Test if file opened 
     if(!infile) 
     { 
      cout << string(12,'*') << " File Open Error " << string(12,'*') << endl; 
      cout << "==> Input file failed to open properly!!\n"; 
      cout << "==> Attempted to open file: " << infname << endl; 
      cout << "==> Please try again...\n"; 
      cout << string(41,'*') << endl; 
      infile.clear(); 
      return 1; 
     } 
    } while(!infile.is_open());  

    return 0; 
} 

回答

2

return 1語句導致程序退出:您是從main()

回國只是不這樣做。

1

嘗試刪除return 1或將其更改爲continuereturn 1main返回代碼執行,而不是循環。