2015-03-24 36 views
0

我附上了我的代碼。如果我刪除了if語句來檢查文件是否被打開,那麼這個序列將起作用。爲什麼它不適用於if語句?另外,如果我第一次提供正確的文件名,它的工作方式如下。它只會在我輸入錯誤的文件名時才掛起。檢查ifstream,出錯後不工作?

感謝您的幫助!

ifstream inputFile(fileName.c_str()); 

if(!inputFile) 
{ 
    cout << "Unable to locate input file, please ensure it is in the working directory" 
     << endl; 
    cout << "Enter the name of your input file (ex. input.txt): "; 
    cin >> fileName; 
    cout << endl; 

    ifstream inputFile(fileName.c_str()); 
} 
else 
{ 
    cout << "Input file opened successfully!" << endl; 
} 
+0

如果用戶輸錯文件名,我想讓他們重新輸入。 – Rich 2015-03-24 21:24:27

回答

1

告訴你的代碼是完全合法的,所以我想你這個「壞名」邏輯後使用inputFile

ifstream inputFile(fileName.c_str()); 

if(!inputFile) 
{ 
    cout << "Unable to locate input file, please ensure it is in the working directory" 
     << endl; 
    cout << "Enter the name of your input file (ex. input.txt): "; 
    cin >> fileName; 
    cout << endl; 

    ifstream inputFile(fileName.c_str()); 
} 
else 
{ 
    cout << "Input file opened successfully!" << endl; 
} 
// USING inputFile here 

但問題是,你仍然有原來的inputFile這裏。 if聲明中的inputFile新的std::ifstream。這可能是更容易地看到,如果你使用一個不同的名稱:

ifstream inputFile(fileName.c_str()); 

if(!inputFile) 
{ 
    cout << "Unable to locate input file, please ensure it is in the working directory" 
     << endl; 
    cout << "Enter the name of your input file (ex. input.txt): "; 
    cin >> fileName; 
    cout << endl; 

    ifstream differentInputFile(fileName.c_str()); //HERE 
} 
else 
{ 
    cout << "Input file opened successfully!" << endl; 
} 

正確的方法來關閉錯誤的文件,並用正確的文件名重新是:

inputFile.close(); 
inputFile.open(fileName.c_str()); 

完整的代碼就變成

ifstream inputFile(fileName.c_str()); 

if(!inputFile) 
{ 
    cout << "Unable to locate input file, please ensure it is in the working directory" 
     << endl; 
    cout << "Enter the name of your input file (ex. input.txt): "; 
    cin >> fileName; 
    cout << endl; 

    inputFile.close(); 
    inputFile.open(fileName.c_str()); 
} 
else 
{ 
    cout << "Input file opened successfully!" << endl; 
} 

建議您啓用警告。我的建議是使用-Wall -Wextra -Wshadow -pedantic -Wfatal-errors(這是gcc和clang)。

+0

由於文件流從未打開過,因此'.clear()'比'.close()'更有意義。 – 2015-03-24 21:34:14

+0

@MooingDuck ifstream inputFile(fileName.c_str());'打開流,不是嗎? http://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream – stefan 2015-03-24 21:35:36

+0

謝謝!有時候是小事情。 – Rich 2015-03-24 21:37:23