2012-02-06 66 views
0

所以我基本上需要我的程序打開一個文件並做一些事情。當程序要求用戶輸入文件名,並且用戶第一次正確輸入文件名時,該操作就起作用。但是,如果用戶輸入了錯誤的名稱,程序會顯示「無效名稱再次嘗試」,但即使用戶正確輸入名稱,也永遠無法打開該文件。這裏的代碼:C++打開文件流

ifstream read_file(file.c_str()); 
while(true) 
{ 
    if(!(read_file.fail())) 
    { 
     ... 
    } 
    else 
    { 
     cout << "Either the file doesn't exist or the formatting of the file is incorrect. Try again.\n>"; 
    } 
    cin >> file; 
    ifstream read_file(file.c_str()); 
} 

什麼問題,有什麼想法?謝謝

回答

5

您將在循環內重新聲明read_file,但循環頂部的代碼始終使用循環外部的read_file。

這是你想要什麼,而不是:

ifstream read_file(file.c_str()); 
while(true) 
{ 
    if(!(read_file.fail())) 
    { 
     ... 
    } 
    else 
    { 
     cout << "Either the file doesn't exist or the formatting of the file is incorrect. Try again.\n>"; 
    } 
    cin >> file; 
    read_file.open(file.c_str()); /// <<< this has changed 
} 
+0

+1。也許值得注意的是,如果(read_file)等於if(!read_file.fail()) – stinky472 2012-02-06 02:45:27

+0

這個工作,非常感謝你 – Richard 2012-02-06 02:46:22

+0

@stinky謝謝你,但我留下的代碼是'因爲它更迂腐 – Gigi 2012-02-06 02:49:36