2012-03-21 96 views
0

程序讀取文件後,從文件中獲取字符,並完成後,詢問用戶是否需要讀取其他文件。如果用戶說是,那麼程序要求提供文件名,但隨後會自動說該文件無法打開並退出循環。請幫幫我。C++後續文件在第一個文件後無法打開

下面是代碼:

do //do while opening the source file fails 
     { 
     cout << "Enter filename of source file: "; 
     cin.getline (filename,51); 
     sourceFile.open(filename); //opens the file with given filename 
     if (sourceFile.fail()) 
      cout << "File could not be opened" << endl; //error if can't open 
     sourceFile.clear(); 
     } 
     while (sourceFile.fail()); //exits if source file doesn't fail 
+1

你嘗試調試?您試圖打開的文件名是否有意義? – 2012-03-21 03:30:29

+0

什麼是一個好的調試器? – 2012-03-21 03:32:14

+1

你會得到什麼錯誤?你在哪個系統上運行? 'gdb'是一個流行的調試器,但是你使用的將取決於你使用的是什麼系統。 – 2012-03-21 03:33:08

回答

1

這個測試:

while (sourceFile.fail()) 

因爲你到達那裏之前,你打電話永遠不會爲真:

sourceFile.clear() 

這將清除任何問題位在iostate中。

我想你只是想擺脫clear()的電話。

+0

它的工作原理是,第一個文件在運行時通過此循環運行時打開正確 – 2012-03-21 03:43:07

+0

@TylerGavin:我認爲問題在於如果打開失敗,循環不會再次請求文件名。 – 2012-03-21 03:46:17

+0

@TylerGavin:我想我現在看到了 - 我相信我在這個答案中有一個問題在你的代碼中(如果打開失敗,你沒有機會再試一次,這就是我認爲循環的意圖是)。然而,聽起來你的直接問題是由arminb的評論解決的。 – 2012-03-21 04:02:13

0

的規範的方法來檢查,如果打開文件失敗是使用std::basic_ios::operator !()

do 
{ 
    cout << "Enter filename of source file: "; 
    std::getline(std::cin, filename); 
    sourceFile.open(filename.c_str()); 
    if (!sourceFile) 
    { 
     cout << "File could not be opened" << endl; 
    } 
} 
while (!sourceFile);